开发者

Subclass-safe class variable

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 situ开发者_StackOverflow中文版ations (which I am unaware of)?


self.__class__.i is correct and sure to work (although i is a poor naming choice).

if the method from which you access i does not use self, you can make it a class method, in which case the first parameter will be the class and not the instance:

class T(object):
    i = 5
    @classmethod
    def p(cls):
        print cls.i

To read the attribute, you can also use self.i safely too. But to change its value, using self.i = value will change the attribute of the instance, masking the class attribute for that instance.


Uh... did you know you can refer to class attributes from instances?

class T(object):
    i = 5

    def p(self):
        print(id(self.i), self.i)

Class methods aside, I just thought of an interesting idea. Why not use a property that accesses the underlying class instance?

class T(object):
    _i = 5

    @property
    def i(self):
        return self.__class__._i

    @i.setter(self, value)
        self.__class__._i = value

Of course this wouldn't prevent users from utilizing an instance's _i seperate from the class's _i.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜