class Human():
def __init__(self,name):
print("human's constructor")
self.name = name
def sing(self):
print("la la")
#child class - separate file
from Human import Human
class SuperHuman(Human):
def __init__(self,name, superpowers = ["super strength", "bulletproof"]):
print("superhuman's constructor")
self.name = name # this line gives error
self.superpowers = superpowers
super().__init__(name)
此代码崩溃,因为在SuperHuman.py中的行" self.name = name" - 无法设置属性。
if __name__ == '__main__':
sup = SuperHuman(name="Tick")
# Instance type checks
if isinstance(sup, Human):
print('I am human')
if type(sup) is SuperHuman:
print('I am a superhero')
name字段已经从Human继承,为什么在调用SuperHuman的构造函数时它不能编译?
答案 0 :(得分:1)
您获得的错误是什么? 最佳实践规定在进行任何初始化工作之前应该调用父构造函数,如此
super(SuperHuman, self).__init__(name)
然后你可以将self.name = name
放在Superhuman构造函数中,因为父类会处理它
答案 1 :(得分:0)
出于某种原因,当我将“name”字段更改为某个随机k时 - 错误消失了。
编译并打印:
class Human:
def __init__(self,k):
print("human's constructor")
self.k = k
print("name assigned: " + str(self.k))
@property
def name(self):
return self.k
if __name__ == '__main__':
sup = Human("Tick")
# Instance type checks
if isinstance(sup, Human):
print('I am human')
更新:我发现了一个愚蠢的错误。方法名称毁了它!我本来应该更专注