2016-08-03 98 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