Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 创建子类的对象时出现问题_Python 3.x_Class_Super - Fatal编程技术网

Python 3.x 创建子类的对象时出现问题

Python 3.x 创建子类的对象时出现问题,python-3.x,class,super,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

我正在尝试运行以下代码:

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()\u 2\u NotWorking!!!.py”, 第18行,在 cat=哺乳动物(6,7,8,9)类型错误:init()接受4个位置参数,但给出了5个


拜托,你能帮我找出我犯了什么错误吗?

这里似乎对子类的工作方式有误解

对于您的基类:

class Animal:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    c = 10
Animal
将这样实例化

snake = Animal(3, 4)
其中,
3
被传递到
\uuuu init\uuuu
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
在它的
\uuuu init\uuuu
方法中只接受2个参数(除了隐式添加的
self
),而您用3调用它

super().__init__(parent, a, b)
super()。
此外,
a
b
此时未分配给任何对象

你可能打算这样做

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)

哺乳动物
类的
方法中的
父类
只是一个普通参数,它不代表
动物

因此,这个
\uuuu init\uuuu
方法将有4个参数:
self
parent
e
f

这就是为什么调用
哺乳动物(6,7,8,9)
时会出现错误的原因,因为调用了5个参数:
哺乳动物类本身
6
7
8
9

此代码不会导致以下错误:

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):
    super().__init__(a, b)
    self.e = e
    self.f = f

  g = 11

snake = Animal(3, 4)
cat = Mammal(6, 7, 8, 9)
Repl.it示例