创建子类的对象时出现问题

时间:2021-04-08 09:35:45

标签: python-3.x class super

我正在尝试运行此代码:

class Animal:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    c = 10

    
class Mammal(Animal):
        def __init__(self, parent, e, f):
                super().__init__(parent, a, b)
                self.e = e
                self.f = f

        g = 11

snake = Animal(3, 4)

cat = Mammal(6, 7, 8, 9)
    

但我收到以下消息:

<块引用>

回溯(最近一次调用最后一次):文件 "C:\Users\Andrea\Desktop\Python 教程\super()_2_NotWorking!!!.py", 第 18 行,在 cat = Mammal(6, 7, 8, 9) TypeError: init() 需要 4 个位置参数,但给出了 5 个

拜托,你能帮我弄清楚我犯了什么错误吗?

2 个答案:

答案 0 :(得分:1)

这里似乎对子类的工作方式存在误解。

对于您的基类:

class Animal:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    c = 10

Animal 会像这样被实例化。

snake = Animal(3, 4)

其中 3 传递给 __init__ a 参数和 4 传递给 b

现在到您的子类。 你有:

class Mammal(Animal):
    def __init__(self, parent, e, f):
        super().__init__(parent, a, b)
        self.e = e
        self.f = f

    g = 11

这没有多大意义,因为基类 Animal 在它的 __init__ 方法中只接受 2 个参数(隐式添加的 self 除外),并且您正在调用它3.

super().__init__(parent, a, b)

super() 在这里大致翻译为我的父类 (self) 的 Animal。 此外,此时 ab 未分配给任何东西。

您可能打算做的是这样的事情。

class Animal:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    c = 10

    
class Mammal(Animal):
    def __init__(self, a, b, e, f):
        # Here we call the Animal().__init__()
        # with the a and b arguments that were passed
        # from cat = Mammal(6, 7, 8, 9)
        super().__init__(a, b)
        self.e = e
        self.f = f
    g = 11

snake = Animal(3, 4)

cat = Mammal(6, 7, 8, 9)
print(cat.a, cat.b)

答案 1 :(得分:1)

parent 类的 __init__ 方法中的

Mammal 只是一个普通参数,并不代表 Animal 类。

这样,这个 __init__ 方法将有 4 个参数:selfparentef

这就是为什么当您调用 Mammal(6, 7, 8, 9) 时会引发错误的原因,因为您调用了 5 个参数:Mammal class itself678、{ {1}}。

此代码不会导致错误:

9

Repl.it 示例 here