I was reading through some code when I came across this particular code where the base class method is printing some attributes which are from derived class, the object which is calling the method is from derived.
class A(object):
def printFreak(self):
print self.derived_attrib
class B(A):
def __init__(self, num):
self.derived_attrib = num
my_obj = B(10)
my_obj.printFreak()
Since I had not seen such behaviour before(like in C++), I am unable to understand this.
Can anyone help me understand this, how this works ? Can this be related to some concept of C++ ?
derived_attribin the object referred to byself, and finds that there is one. It would work in C++ as long asderived_attribwas declared as field ofAand then assigned inB, because then the compiler would be able to figure out whatself.derived_attribmeant inA's method.printFreakmethod were an attribute of the child class that defines.derived_attrib. In Python, it's quite common for attributes to be added dynamically to class instances, but it's still a bit smelly for a method to make assumptions about attributes that aren't part of the class definition (either in the class itself or defined in one of its parents).