Je t’embrasse Salutations from Silicon Valley, California

28May/100

Using a Property to get a Class name into an Attribute

For one reason or another, I found myself in a slight predicament. I needed to get the name of my class into an attribute.

Thanks to Google + KyLev I managed to procure a workable solution:

class Problem(object):
    moduleIndex = 0
    def __init__(self):
        self.__class__.moduleIndex = self.__class__.moduleIndex + 1

class Solution(object):
    moduleIndex = 0
    moduleName = property(fget=lambda self: self.__class__.__name__)
    def __init__(self):
        self.__class__.moduleIndex = self.__class__.moduleIndex + 1
        print "[%s] %s"%(self.moduleIndex, self.moduleName)

if __name__ == "__main__": t = Solution()
Filed under: Python No Comments