I can do:
class T(object):
i = 5
# then use the value somewhere in a function
def p(self):
print id(i), T.i
.. but, if I happen to subclass T ..
class N(T):
pass
.. then N.i will in fact be T.i. I found a way to deal with this:
class T(object):
i = 5
def p(self):
print self.__class__.i
.. is this correct and sure to work? Or can it produce unexpected behavior in some situations (which I am unaware of)?
self.__class__.iis correct and sure to work (althoughiis a poor naming choice).if the method from which you access
idoes not use self, you can make it a class method, in which case the first parameter will be the class and not the instance:To read the attribute, you can also use
self.isafely too. But to change its value, usingself.i = valuewill change the attribute of the instance, masking the class attribute for that instance.