简体   繁体   中英

Python: Using derived class attributes in base class

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++ ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM