Gio*_*iuc 5 python oop inheritance super python-3.x
假设我有一些Python代码:
class Mother:
def __init__(self):
print("Mother")
class Father:
def __init__(self):
print("Father")
class Daughter(Mother, Father):
def __init__(self):
print("Daughter")
super().__init__()
d = Daughter()
Run Code Online (Sandbox Code Playgroud)
此脚本打印"女儿".反正是否确保调用基类的所有__init__方法?我想出的一个方法是:
class Daughter(Mother, Father):
def __init__(self):
print("Daughter")
for base in type(self).__bases__:
base.__init__(self)
Run Code Online (Sandbox Code Playgroud)
这个脚本打印"女儿","母亲","父亲".使用super()或其他方法有一个很好的方法吗?
Raymond Hettinger在PyCon 2015的Super Considered Super演讲中解释得非常好.简短的回答是肯定的,如果你这样设计,并super().__init__()
在每个班级打电话
class Mother:
def __init__(self):
super().__init__()
print("Mother")
class Father:
def __init__(self):
super().__init__()
print("Father")
class Daughter(Mother, Father):
def __init__(self):
super().__init__()
print("Daughter")
Run Code Online (Sandbox Code Playgroud)
这个名字super
很不幸,它确实通过基类运行.
归档时间: |
|
查看次数: |
123 次 |
最近记录: |