理解python继承参数有困难

2024-04-26 00:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过读一些不同的教程,但我还是想不通。我有两个简单的课程。动物和猫。你知道吗

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类实例的原始基类(Animal?为什么?那么,如何向Cat类实例提供它所需的age变量呢?你知道吗

我试着做:

c = Cat('Molly', 10)

但它抱怨太多的争论。其次,为什么不能调用Cat类的__init__函数?它应该打印“年龄是…”。只是从来没有。你知道吗

编辑:多亏了玛蒂恩·皮特斯,它才得以运转!以下是更新后的代码(适用于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()

Tags: 实例nameselfformatageinitisdef
1条回答
网友
1楼 · 发布于 2024-04-26 00:19:24

你拼错了__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

相关问题 更多 >