2016-08-03 95 views
0

这是一个练习代码。除了如何进行权重比较外,我了解所有内容。我想要另一个重量是40并打印“Spot Wins!”面向对象编程(Python)代码

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

您不要在构造函数中放置'self.battle(40)'。你稍后在Pet类的**实例**上调用'spot.battle(Pet(...))'。 –

回答

1

battle()需要与.weight属性(如Pet)的东西,但你传递一个数字(integer)。你不应该把它放在__init__函数中,因为其中一种方法是创建另一个Pet,它试图使另一个Petbattle广告无限。

但是,如果您在spot之后添加另一个Pet,Lassie并告诉spot.battle(Lassie),它会将它们与您的函数进行比较。

+0

谢谢我现在得到它 – Mia