这是一个练习代码。我理解除了如何使权重进行比较之外的一切。我希望其他重量为40并打印“Spot Wins!”
class Pet:
def __init__(self,myname,mykind,myweight,mycost):
self.name = myname
self.kind = mykind
self.weight = myweight
self.cost = mycost
self.speak()
self.isexpensive()
# self.battle(40) This is where the error happens
def speak(self):
if self.kind == 'dog':
print('Woof!')
elif self.kind == 'cat':
print('Meow!')
else:
print('I am mute')
def battle(self,other):
if self.weight > other.weight:
print(self.name + ' wins!')
else:
print(other.name + ' wins!')
def grow(self):
self.weight = self.weight + 5
def isexpensive(self):
if self.cost > 500:
return True
else:
return False
spot = Pet('Spot','dog',50,550)
答案 0 :(得分:1)
battle()
需要具有.weight
属性的内容(例如Pet
),但您传入的是一个数字(integer
)。您不应该将其放在__init__
函数中,因为其中一种方法是创建另一个Pet
,它会尝试创建另一个Pet
到battle
广告。
但是,如果您在Pet
之后添加其他Lassie
,spot
并告诉spot.battle(Lassie)
,则会将其与您的功能进行比较。