无法理解python继承参数

时间:2014-06-27 15:05:12

标签: 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):
        print('Meowwww!')



c = Cat('Molly')
c.talk()

输出是:

Meowwww!

代码运行,但我有点困惑。我用c = Cat('Molly')创建了一个cat类的实例。因此,以某种方式使用"Molly"作为Cat()类实例的参数,它将"Molly"提供给原始基类(Animal而不是我创建的Cat类实例?为什么?那么如何为Cat类实例提供所需的age变量?

我尝试过:

c = Cat('Molly', 10)

但它抱怨说太多论点。其次,为什么不会调用Cat类的__init__函数?它应该打印"年龄是......"。它永远不会。

编辑:得到它的工作,感谢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()

1 个答案:

答案 0 :(得分:6)

你拼错了__init__

def __init___(self, age):
#   12    345

最后是3个双重下划线,而不是必需的2。

因此,Python不会调用它,因为它不是它正在寻找的方法。

如果要传入年龄和名称,请为方法指定另一个参数,然后使用名称调用父__init__

class Cat(Animal):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
相关问题