Python 多重继承。这是一个错误吗?
Python multi-inheritance. Is this a bug?
在下面的示例中,我希望看到:
CarChild1
CarChild2
但它打印:
CarChild1
CarChild1
场景是我有一个 class 继承了 2 个 classes。
它需要以正确的顺序调用两个父 class 的 run()
函数,但由于某些原因,它只调用了第一个父 class 的函数。
下面的示例代码说明了这个问题:
class CarChild1:
def run(self):
self._print_name()
def _print_name(self):
print('CarChild1')
class CarChild2:
def run(self):
self._print_name()
def _print_name(self):
print('CarChild2')
class CarChild3(CarChild1, CarChild2):
def run(self):
CarChild1.run(self)
CarChild2.run(self)
carChild3 = CarChild3()
carChild3.run()
您对 self._print_name()
的调用将根据其 class 层次结构调用对象的 _print_name
方法,不一定是您在同一 class 中定义的方法从中调用它。
如果您特别希望 CarChild2
使用 CarChild2
中声明的 _print_name
方法,您可以调用 CarChild2._print_name(self)
。或者您可以为不同的 _print_name
方法指定不同的名称,因为您希望它们独立工作。
或 如果您调用打印方法 __print_name
(带有双下划线前缀)而不是 _print_name
那么 Python 将在内部改变他们的名字,以便在每个 class 中调用正确的名字,并且不能*在它之外调用。 (这些方法基本上是 class 私有的。)
* 他们可以,但只能绕过名称修改机制
在下面的示例中,我希望看到:
CarChild1
CarChild2
但它打印:
CarChild1
CarChild1
场景是我有一个 class 继承了 2 个 classes。
它需要以正确的顺序调用两个父 class 的 run()
函数,但由于某些原因,它只调用了第一个父 class 的函数。
下面的示例代码说明了这个问题:
class CarChild1:
def run(self):
self._print_name()
def _print_name(self):
print('CarChild1')
class CarChild2:
def run(self):
self._print_name()
def _print_name(self):
print('CarChild2')
class CarChild3(CarChild1, CarChild2):
def run(self):
CarChild1.run(self)
CarChild2.run(self)
carChild3 = CarChild3()
carChild3.run()
您对 self._print_name()
的调用将根据其 class 层次结构调用对象的 _print_name
方法,不一定是您在同一 class 中定义的方法从中调用它。
如果您特别希望 CarChild2
使用 CarChild2
中声明的 _print_name
方法,您可以调用 CarChild2._print_name(self)
。或者您可以为不同的 _print_name
方法指定不同的名称,因为您希望它们独立工作。
或 如果您调用打印方法 __print_name
(带有双下划线前缀)而不是 _print_name
那么 Python 将在内部改变他们的名字,以便在每个 class 中调用正确的名字,并且不能*在它之外调用。 (这些方法基本上是 class 私有的。)
* 他们可以,但只能绕过名称修改机制