python - Subclass-safe class variable -
python - Subclass-safe class variable -
i can do:
class t(object): = 5 # utilize value somewhere in function def p(self): print id(i), t.i
.. but, if happen subclass t
..
class n(t): pass
.. n.i
in fact t.i
. found way deal this:
class t(object): = 5 def p(self): print self.__class__.i
.. right , sure work? or can produce unexpected behavior in situations (which unaware of)?
self.__class__.i
right , sure work (although i
poor naming choice).
if method access i
not utilize self, can create class method, in case first parameter class , not instance:
class t(object): = 5 @classmethod def p(cls): print cls.i
to read attribute, can utilize self.i
safely too. alter value, using self.i = value
alter attribute of instance, masking class attribute instance.
python
Comments
Post a Comment