Reputation: 1003
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++ ?
Upvotes: 5
Views: 2376
Reputation: 59113
In Python, attributes are resolved at run-time, so it simply looks for an attribute called derived_attrib
in the object referred to by self
, and finds that there is one.
It would work in C++ as long as derived_attrib
was declared as field of A
and then assigned in B
, because then the compiler would be able to figure out what self.derived_attrib
meant in A
's method.
Upvotes: 3