Search code examples
pythonoopinheritancemember

Adding an instance variable to a base class in Python


I have a base class A, inherited by classes B and C, from which I was trying to set an instance variable. Such variable is used by methods from base class A as follows.

class A(object):
    def foo(self):
        print(self.value)

class B(A):
    value = "B"

class C(A):
    value = "C"

>>> b = B()
'B'
>>> c = C()
'C'

I understand function foo will only be evaluated during execution, which is fine as long as I do not invoke foo straight from an instance of A. Yet, I fail to grasp how value = "B" and value = "C" manage to become self.value = "B" and self.value = "C".

Sorry if this is naive question; I have been far from python for quite a while now, and really had not seen anything quite like it. I'm using Python version 2.7.12.


Solution

  • You cannot add an instance variable to a base class in Python, because instance variables can only be added to instances, not classes.

    In your example, "value" is a class variable. In Python, when there is no instance variable with a given name, it falls back to the class variable with that name. However, if you assigned a new value to b.value, that would create an instance variable on b. B.value would be unaffected, as would any new instances of B.

    I didn't find an authoritative reference for the behavior, but here's an article about it. https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide