最近我学到了类和子类,我尝试了一些代码,但是一直都有错误。
AttributeError:输入对象‘刺客’没有属性‘武器’
在这里,代码:我认为继承可能有问题。
class Character(object):
def __init__(self,name,**kwargs):
self.name=name
self.hp=500
self.speed=50
for key,value in kwargs.items():
setattr(self,key,value)
class Warrior(Character):
def __init__(self,**kwargs):
self.weapon="Sword"
self.armor="Giant Skin"
super().__init__(name,hp,**kwargs)
def hp(self,new_hp):
self.new_hp=hp+500
if hp > 900:
print("Youre very healty!")
class Spearman(Warrior,Character):
def __init__(self,**kwargs):
self.weapon="Spear"
self.armor="Heavy Armor"
super().__init__(name,hp,**kwargs)
def rage(self):
if weapon == "Spear":
print("YOU ARE IN RAGE!")
class Thief(Character):
def __init__(self,**kwargs):
self.weapon="Dagger"
self.armor="Clean Fit"
super().__init__(name,hp,**kwargs)
def Avoidance(self,speed):
if speed > 80:
print("Avoided from enemy!")
else:
print("not fast enough!")
class Assassin(Thief,Character):
def __init__(self,weapon,armor,**kwargs):
self.weapon="Slim Dag"
self.armor="Cloak of mystery"
super().__init__(name,hp,**kwargs)
dani=Assassin
omer=Spearman
print(dani.weapon)
print(dani.armor)
print(dani.hp)
print(dani.speed)
dani.Avoidance(100)发布于 2017-06-27 21:16:01
1。在python中,为了创建类的实例,语法如下:
dani = Assassin("mg7", "cloak")( Assassin类只定义刺客的特征以及它能做什么。实际上创建一个名为实例化的刺客)
2。在刺客的init方法中,您将self.weapon和self.armor设置为特定值。那么,如果你不使用武器和装甲,你为什么要得到它们的价值呢?
3。在类的init方法中,您正在使用不存在的名称和hp变量调用超级变量。
4。也许这是为了一个独特的目的,但至少我没有理由继承盗贼和角色,因为Thief本身已经是字符的子类。( Spearman和角色也是如此)
5。根据python惯例,方法名称应该以小写开始(def避免而不是避免)。
6。如果Thief.avoidance不使用自参数,则应该将其更改为静态方法,方法是在定义的基础上编写@staticmethod。(并从方法参数中删除self )。
7。在几种方法中,您无需使用“self”来访问实例变量。虽然这在Java和C#中有效,但在java中,必须使用self参数(这是指向实例的指针)访问实例变量。
想了解更多信息,请看这里:https://docs.python.org/2/tutorial/classes.html
https://stackoverflow.com/questions/44789985
复制相似问题