2016-08-03 7 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()의 (a Pet 같이) .weight 속성으로 뭔가를 필요로하지만, 당신은 수 (integer)를 전달하고 있습니다. 을 ad infinium으로 만들려고 다른 Pet을 만드는 방법 중 하나이기 때문에 __init__ 함수 안에 넣으면 안됩니다.

Pet, Lassiespot 다음에 추가하고 spot.battle(Lassie)이라고 말하면 기능과 비교합니다.

+0

감사합니다. 지금 받으십시오. – Mia