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示例