maligree
maligree

Reputation: 6147

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 situations (which I am unaware of)?

Upvotes: 3

Views: 1124

Answers (2)

gurney alex
gurney alex

Reputation: 13645

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.

Upvotes: 1

JAB
JAB

Reputation: 21089

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.

Upvotes: 1

Related Questions