我是一个Python新手,试图理解继承方法背后的哲学/逻辑。问题最终涉及为什么以及何时必须使用__init__
子类中的方法。例子:
看来从超类继承的子类不需要有自己的构造函数(__init__
) 方法。下面,狗继承了哺乳动物的属性(名字、年龄)和方法(发出声音)。您甚至可以添加一个方法(do_a_trick
)一切似乎都“应该”进行。
但是,如果我想像在 Cats 类中尝试那样在子类中添加新属性,则会收到一条错误消息,指出“self”未定义。然而我在狗类的定义中使用了“self”。差异的本质是什么?
它似乎定义了猫,因为我希望我需要使用__init__(self,name)
and super()__init__(name)
。为什么有区别?
class Mammals(object):
def __init__(self,name):
self.name = name
print("I am a new-born "+ self.name)
self.age = 0
def makenoise(self):
print(self.name + " says Hello")
class Dogs(Mammals):
def do_a_trick(self):
print(self.name + " can roll over")
class Cats(Mammals):
self.furry = "True" #results in error `self' is not defined
mymammal = Mammals("zebra") #output "I am a new-born zebra"
mymammal.makenoise() #output "zebra says hello"
print(mymmmal.age) #output 0
mydog = Dogs("family pet") #output "I am a new-born family pet"
mydog.makenoise() #output "family pet says hello"
print(mydog.age) # output 0
mydog.do_a_trick() #output "family pet can roll over"
显式的比隐式的好。 https://www.python.org/dev/peps/pep-0020/
但是,您可以执行以下操作:
class Dogs(Mammals):
def __init__(self):
#add new attribute
self.someattribute = 'value'
Mammals.__init__(self)
or
class Dogs(Mammals):
def __init__(self):
#add new attribute
self.someattribute = 'value'
super(Mammals, self).__init__()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)