gpt4 book ai didi

python - 类型错误 : __init__() missing 2 required positional arguments: 'no_of_arrows' and 'email'

转载 作者:行者123 更新时间:2023-12-04 08:10:18 28 4
gpt4 key购买 nike

我使用多重继承功能编写了一个 python 3.9 代码。
我在 Anaconda Navigator 中使用 Jupyter Notebook 编写和运行此代码。
它在向导类 中给出了一个 TypeError初始化 () 方法:


# multiple inheritance

class User:
def __init__(self, email):
self.email = email

def sign_in(self):
print('Logged in.')

def attack(self):
print('User attack.')


class Wizard(User):
def __init__(self, name, power, email):
super().__init__(email)
self.name = name
self.power = power

def attack(self):
super().attack()
print(f'Attacking with power of {self.power}.')


class Archer(User):
def __init__(self, name, no_of_arrows, email):
super().__init__(email)
self.name = name
self.no_of_arrows = no_of_arrows

def attack(self):
print(f'Attacking with arrows. Arrows left - {self.no_of_arrows}.')

def check_arrows_count(self):
print(f'{self.no_of_arrows} left.')

def run(self):
print('run')


class HybridAttacker(Wizard, Archer):
def __init__(self, name, power, no_of_arrows, email):
Wizard.__init__(self, name, power, email)
Archer.__init__(self, name, no_of_arrows, email)


hybrid_attacker = HybridAttacker('Tom', 50, 20, 'tom@gmail.com')
print(hybrid_attacker)

这是带有 TypeError 的输出:

*TypeError Traceback (most recent call last) <ipython-input-11-4769f9f86581> in <module>
45
46
---> 47 hybrid_attacker = HybridAttacker('Tom', 50, 20, 'tom@gmail.com')
48 print(hybrid_attacker)
<ipython-input-11-4769f9f86581> in __init__(self, name, power, no_of_arrows, email)
41 class HybridAttacker(Wizard, Archer):
42 def __init__(self, name, power, no_of_arrows, email):
---> 43 Wizard.__init__(self, name, power, email)
44 Archer.__init__(self, name, no_of_arrows, email)
45
<ipython-input-11-4769f9f86581> in __init__(self, name, power, email)
14 class Wizard(User):
15 def __init__(self, name, power, email):
---> 16 super().__init__(email)
17 self.name = name
18 self.power = power
TypeError: __init__() missing 2 required positional arguments: 'no_of_arrows' and 'email'*

请帮我找出错误是什么。
当我注释掉 super() 时。 初始化 (电子邮件)在向导类 初始化 () 方法,代码运行没有任何错误。
提前致谢。

最佳答案

我不确定你想在这里实现什么,但你必须记住所有 __init__将在那里被 HybridAttacker 调用.您错过了每个函数的参数,因此您需要使用 **kwargs然后就得到你需要的。
所以你的 __init__功能可能看起来像

class Wizard(User):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.name = kwargs.get('name')
self.power = kwargs.get('power')
HybridAttacker可以为每个父级的 init 指定参数:
class HybridAttacker(Wizard, Archer):
def __init__(self, name, power, no_of_arrows, email):
Wizard.__init__(self, name=name, power=power, email=email)
Archer.__init__(self, name=name, no_of_arrows=no_of_arrows)

关于python - 类型错误 : __init__() missing 2 required positional arguments: 'no_of_arrows' and 'email' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66007993/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com