简体   繁体   English

调用同一基类中定义的另一个方法的基类的方法可能最终调用覆盖它的派生类的方法

[英]A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it

I am reading python documentaitin at: https://docs.python.org/3/tutorial/classes.html我正在阅读 python 文档: https : //docs.python.org/3/tutorial/classes.html

I am having trouble understanding the following:我无法理解以下内容:

Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.由于方法在调用同一对象的其他方法时没有特殊权限,因此调用同一基类中定义的另一个方法的基类方法可能最终会调用覆盖它的派生类的方法。 (For C++ programmers: all methods in Python are effectively virtual.) (对于 C++ 程序员:Python 中的所有方法都是有效的虚拟方法。)

Say base class X has method A that calls method B in the same base class.假设基类 X 有方法 A 调用同一基类中的方法 B。

Now a derived class Y, say has method B, and user invokes YA().现在派生类 Y,假设有方法 B,用户调用 YA()。 Then, method A from Class X will be invoked and it will call method B from Class Y?那么,X 类中的方法 A 将被调用,而 Y 类中的方法 B 将被调用? Is this what author is trying to say?这是作者想表达的吗?

I assume this it what he means我想这就是他的意思

In [8]: class A:
   ...:     def foo(self):
   ...:         print ('foo')
   ...:         self.bar()
   ...:     def bar(self):
   ...:         print ('bar')
   ...:

In [9]: class B(A):
   ...:     def bar(self):
   ...:         print('bar but in b')
   ...:

In [10]: obj = B()

In [11]: obj.foo()
foo
bar but in b

In line 11, obj.foo() calls foo in class B, since its non existent, it goes to foo in class A, which then calls bar , since B has bar it calls it instead of bar in class A在第 11 行,obj.foo() 在类 B 中调用foo ,因为它不存在,所以它转到类 A 中的 foo,然后调用bar ,因为 B 有bar它调用它而不是类 A 中的bar

If you have access to a debugger like pycharm it would be easier to follow it step by step如果您可以访问像 pycharm 这样的调试器,那么一步一步地遵循它会更容易

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

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