理解python继承参数有困难
我试着读了一些不同的教程,但我还是不明白。我有两个简单的课程。动物和猫理解python继承参数有困难,python,class,object,inheritance,Python,Class,Object,Inheritance,我试着读了一些不同的教程,但我还是不明白。我有两个简单的课程。动物和猫 class Animal: def __init__(self, name): self.name = name class Cat(Animal): def __init___(self, age): self.age = age print('age is: {0}'.format(self.age)) def talk(self):
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init___(self, age):
self.age = age
print('age is: {0}'.format(self.age))
def talk(self):
print('Meowwww!')
c = Cat('Molly')
c.talk()
输出为:
Meowwww!
代码运行,但我有点困惑。我用c=cat'Molly'创建了一个cat类的实例。因此,通过使用Molly作为Cat类实例的参数,它将Molly提供给原始的基类动物,而不是我创建的Cat类实例?为什么?那么,如何向Cat类实例提供它所需的年龄变量呢
我试着做:
c = Cat('Molly', 10)
但它抱怨太多的争论。其次,为什么不调用Cat类的uuu init_uuuu函数?它应该是。。。。只是从来没有
编辑:感谢Martijn Pieters,它成功了!以下是使用python3的更新代码:
class Animal():
def __init__(self, name):
self.name = name
print('name is: {0}'.format(self.name))
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age
print('age is: {0}'.format(self.age))
def talk(self):
print('Meowwww!')
c = Cat('Molly', 5)
c.talk()
您拼错了uu init_uuuuu:
结尾是3个双下划线,不是要求的2个
因此,Python不会调用它,因为它不是它正在寻找的方法
如果要同时传入年龄和名称,请为该方法提供另一个参数,然后仅使用名称调用父项_init _;:
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age
虽然我相信动物也需要从对象继承来使用super-see。此外,在Python3.0+中,super只能在没有参数的情况下调用。否则,子类和self也必须通过。查看更多信息。@AMacK:是的,但是OP在这里使用python3,使用print作为函数。对象在Python 3中是隐式的,所有类都是new-style.True,但在以前的版本中也可以选择使用print函数。但是我不认为隐式对象父对象可以追溯到以前。@AMacK:不,确实不能。在Python2中,必须使用super的显式形式并从对象继承。
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name)
self.age = age