我有此代码,并且其中没有错误:
class Weapon(object): #don't know if this has to inherit from (object)
def __init__(self,weaponName):
self.weaponName=weaponName
class Character(object):
def __init__(self,name,weaponName):
self.name=name
self.weapon=Weapon(weaponName)
class NPC(Character):
def __init__(self,name,weaponName):
super().__init__(name,weaponName)
class Friendly(NPC):
def __init__(self,name,weaponName):
super().__init__(name,weaponName)
sword=Weapon('sword')
guard=NPC('Bob','sword')
print(guard.weapon.weaponName)
print(guard.name)
但是,当我尝试向Weapon类添加Damage属性时:
class Weapon(object):
def __init__(self,weaponName,weaponDamage):
self.weaponName=weaponName
self.weaponDamage=weaponDamage
class Character(object):
def __init__(self,name,weaponName):
self.name=name
self.weapon=Weapon(weaponName)
class NPC(Character):
def __init__(self,name,weaponName):
super().__init__(name,weaponName)
class Friendly(NPC):
def __init__(self,name,weaponName):
super().__init__(name,weaponName)
sword=Weapon('sword',15)
guard=NPC('Bob','sword')
print(guard.weapon.weaponName)
print(guard.name)
我得到:
Traceback (most recent call last):
File "D:\Python files\inheritance test.py", line 21, in <module>
guard=NPC('Bob','sword')
File "D:\Python files\inheritance test.py", line 13, in __init__
super().__init__(name,weaponName)
File "D:\Python files\inheritance test.py", line 9, in __init__
self.weapon=Weapon(weaponName)
TypeError: __init__() missing 1 required positional argument: 'weaponDamage'
这是为什么?我不想在角色初始化中的任何地方实际引用weaponDamage,我只想在以后的功能(例如攻击等)中使用它。如果我有多种武器,我想说“此友谊实例具有x武器”,然后从那里通过查看Weapon类的x实例知道武器的伤害是什么。
最佳答案
你问:
这是为什么?
您在Weapon.__init__()
中指定它需要weaponDamage
作为参数。如果在任何地方构造Weapon
的实例,则需要提供weaponDamage
的值。
您可以通过在weaponDamage
中为Weapon.__init_()
提供默认值来纠正错误。
class Weapon(object):
def __init__(self,weaponName,weaponDamage=0):
self.weaponName=weaponName
self.weaponDamage=weaponDamage