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.
valueinstead ofself.value? Why doesself.valuework?valueis not defined in any scope. That would raise aNameError. You can useMyClass.valueormy_instance.value, but justvaluewill try to find a local variable or a global variable. When a attribute on an instance is accessed, first it checks the namespace of the instance, if it isn't found, it checks the namespace of the class, and then all the classes in the MRO until the name is resolved or anAttributeErroris raised. That's inheritance in a nutshell. See this question