2016-08-03 15 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()は(Petのような).weight属性で何かを必要としますが、数(integer)に渡してい。 をbattle ad infiniumにもう1つ作成しようとする別のPetを作成する方法の1つがあるため、__init__関数の内部に入れないでください。

Pet,Lassiespotの後に追加してspot.battle(Lassie)と言うと、それはあなたの機能と比較されます。

+0

ありがとう私は今それを得る – Mia

関連する問題