python - 如果我们想强制调用父类方法,使用 Classname.method 名称而不是 super() 是唯一的解决方案吗?
问题描述
有什么方法可以确保在创建 B 的实例或 B 的任何子类的实例时,必须调用来自 A 的测试方法?
当前代码如下:
class A:
def test(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
super().test()
class C(A):
def test(self):
print(" test of C called ")
#super().test()
class E(B):
def test(self):
print(" test of E called ")
super().test()
class D(B,C):
pass
obj1=B()
obj1.test()
print('xxxxxx')
obj3=E()
obj3.test()
print('xxxxxx')
obj2=D()
obj2.test()
输出:
B
A
xxxxxx
E
B
A
xxxxxx
B
C
如何在最后一种情况下确保 A 输出。将 B 类的测试方法更改为 A.test() 而不是 super().test() 是唯一的解决方案吗?
这意味着第三个输出将不再是 B、C,现在是 B、A。有没有办法保留 B、C、A?
解决方案
您未能使用super
inC.test
会破坏最终导致A.test
被调用的调用链。super
支持协作继承,这意味着所有类都需要通过super
一致的使用来协作。
class A:
def test(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
super().test()
class C(A):
def test(self):
print(" test of C called ")
super().test()
class E(B):
def test(self):
print(" test of E called ")
super().test()
class D(B,C):
pass
现在,当您调用 时obj2.test()
,您将从B.test
(因为D.test
未定义)开始。调用super
inB.test
导致C.test
被调用,调用 inC.test
将导致A.test
被调用。
推荐阅读
- python - 我想在 Django Rest Framework 中获取 ForeignKey 的 url
- javascript - instance.render 不是 reactjs 中的函数错误
- javascript - Angular 6 setTimeout Module not found: Error: Can't resolve 'timers'
- javascript - Python相当于选择第一个非空参数
- go - 使用 gorilla mux 提供静态 html 文件
- python - Pandas Dataframe - 更改数据结构(重新组织)
- sql-server - EF 2.1 中的播种日期
- google-apps-script - 在 Google 表格插件中,如何检查用户是否已购买订阅?
- c++ - 如何区分使用运算符调用的常量和非常量方法
- java - 从 javax.enterprise.context 而非 javax.faces.bean 导入 sessionbean