简体   繁体   English

Python:在基类中使用派生类属性

[英]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. 由于我之前没有见过这样的行为(比如在C ++中),我无法理解这一点。

Can anyone help me understand this, how this works ? 任何人都可以帮我理解这一点,这是如何工作的? Can this be related to some concept of C++ ? 这可能与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. 在Python中,属性在运行时被解析,因此它只是在self引用的对象中查找名为derived_attrib的属性,并发现有一个属性。

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. 只要derived_attrib被声明为A字段然后在B分配,它就可以在C ++中工作,因为编译器将能够找出A的方法中self.derived_attrib含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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