我在阅读关于classes的Python文档时遇到了这一段,但我不确定:
Derived classes may override methods of their base classes. 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.)
示例:
class A:
def foo(self):
self.bar()
def bar(self):
print "from A"
class B(A):
def foo(self):
self.bar()
def bar(self):
print "from B"
这是否意味着类Aobj = A()
的对象可以以某种方式结束打印“from B”?我读对了吗?如果这不合理,我道歉。对于python如何处理继承和重写,我有点困惑。谢谢!
输出:
不,这意味着如果您有以下对象:
你也知道
然后将
from B
打印为foo()
(在基类中定义),调用bar()
(也在基类中定义),但在派生类中重写。至少我是这样读的。
不,超类不可能知道子类的任何信息。它的意思是,如果你实例化子类B,它继承了一个方法
foo()
,并重写了一个方法bar()
,那么当你调用foo()
时,它将调用B中的bar()
定义,而不是a中的bar()
定义。这不是超类编写器想要的-他希望对bar()
的调用转到他自己的定义。相关问题 更多 >
编程相关推荐