2014-04-25 1 views
2

아래 코드는 테스트 케이스입니다. 내 코드는파이썬 오류 클래스

내가 필요한 것은 self.teach 내에서 내 오류입니다. 아래의 테스트 케이스에서, 필자 코드는 "야옹 야옹은 야프와 야단 법석을 말합니다"라고 할 때 "야옹 야옹은 야프 풀이라고 말합니다."라고 말합니다. 다른 테스트 케이스가 정확합니다.

 #test cases  
meow_meow = Tamagotchi("meow meow") 
meow_meow.teach("meow") 
meow_meow.play() 
>>>>"meow meow says meow" 
meow_meow.teach("purr") 
meow_meow.teach("meow") 
meow_meow.play() 
>>>>'meow meow says meow and purr' #My own code state " meow meow says meowpurr" 

내 코드 사용 :

class Tamagotchi(object): 
    def __init__(self, name): 
     self.name = name 
     self.words = str(self.name) + " says " 
     #check alive, dead within all the methods 
     self.alive = True 

    #trouble portion 
    def teach(self, *words): 
     if self.alive == False: 
      self.words = self.name + " is pining for the fjords" 
      return self.words 
     else: 
      listing = [] 
      for word in words: 
       listing.append(str(word)) 
      B = " and ".join(listing) 
      self.words += B 


    def play(self): 
     return self.words 
    def kill(self): 
     if self.alive == True: 
      self.words = self.name + " is pining for the fjords" 
      self.alive = False 
      return self.name + " killed" 
     else: 
      return self.name + " is pining for the fjords" 

감사를

+0

'90s Nostalgia ... :) –

답변

2

문자열로 words 보관하지 마십시오; 대신 목록으로 저장하고 .play()을 실행할 때 ' and '으로 목록에 참여하십시오.

class Tamagotchi(object): 
    def __init__(self, name): 
     self.name = name 
     self.words = [] 
     self.alive = True 

    def teach(self, *words): 
     self.words.extend(words)  

    def kill(self): 
     self.alive = False 

    def play(self): 
     if self.alive: 
      return '{} says {}'.format(self.name, ' and '.join(self.words)) 
     else: 
      return '{} is pining for the fjords'.format(self.name) 

테스트 케이스 아무것도 반환 Tamagotchi.teach()Tamagotchi.kill()을 필요로하지 않는 것이 당신의 다마고치가 아직 살아 있는지 테스트 할 위치에 있습니다.