我试图了解OOP中的多态性,我建立了一个怪物父类,从这个主类中您可以继承oarc,巫师和巨人。.但是主要的攻击方法是在父怪物类中编码的,并且只有一个放在变量名称 basic_attack
中的字符串问题是,当我在子类的oarc,巫师或巨人中调用此攻击变量时,出现此错误'oarc'的实例没有'basic_attack'memberpylint(no-member)
请放轻松,请随时在下面查看我的代码。
class monster:
def __init__(self, damage, speed, skill):
self.damage = damage
self.speed = speed
self.skill = skill
def attack(self):
basic_attack = "you've been attacked by "
return basic_attack
class oarc(monster):
def __init__(self, damage, speed, skill, oarc_data):
super().__init__(damage, speed, skill)
self.oarc_data = oarc_data
def attack(self):
return self.basic_attack + self.oarc_data
class wizard(monster):
def __init__(self, damage, speed, skill, wizard_data):
super().__init__(damage, speed, skill)
self.wizard_data = wizard_data
def attack(self):
return self.basic_attack + self.wizard_data
class giant(monster):
def __init__(self, damage, speed, skill, giant_data):
super().__init__(damage, speed, skill)
self.giant_data = giant_data
def attack(self):
return self.basic_attack + self.giant_data
oarc_object = oarc(56, 150, 'ugly', 'Oarc')
wizard_object = wizard(20, 100, 'fast', 'Wizard')
giant_object = giant(100, 20, 'strong', 'Giant')
list = [oarc_object, wizard_object, giant_object]
for each in list:
print(each.attack)
print(oarc_object.attack())
答案 0 :(得分:0)
好的,基本上看起来self.basic_attack
从未设置。可以使用self.basic_attack = basic_attack
的{{1}}中的def __init__()
进行修复。
class Monster
中basic_attack = "you've been attacked by "
下的def attack()
与设置class Monster
不同。 basic_attack
被约束为basic_attack
函数。
例如,让我们对非OOP代码进行抽象;
attack()
现在,如果我们没有在# define a
a = 0
def test():
# define out
a = 2
# output out
return a
print(test())
>> 2
print(a)
>> 0
中重新定义a
:
test()
现在,如果# set a
a = 0
# define test
def test():
return a
print(test())
>> 0
print(a)
>> 0
仅在a
中定义;
test()
希望这会有所帮助。祝你有美好的一天!
这是Python OOP的简短介绍; Quick & easy; Object-oriented Programming from the ground up with Examples from Pikachu and Bay Area Rapid Transit (BART)
这是将OOP发布到LinkedIn的更深入的应用; LinkedOut