面向对象编程(Python)代码

时间:2016-08-03 15:54:44

标签: python oop

这是一个练习代码。我理解除了如何使权重进行比较之外的一切。我希望其他重量为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)

1 个答案:

答案 0 :(得分:1)

battle()需要具有.weight属性的内容(例如Pet),但您传入的是一个数字(integer)。您不应该将其放在__init__函数中,因为其中一种方法是创建另一个Pet,它会尝试创建另一个Petbattle广告。

但是,如果您在Pet之后添加其他Lassiespot并告诉spot.battle(Lassie),则会将其与您的功能进行比较。

相关问题