2017-11-21 1 views
-1

사다리가 있습니다. 사다리의 3 단은 원숭이이고, 5 단에는 다람쥐가 있고, 8 단에는 비둘기가 있고, 15 단에는 독수리가 있고, 17 단에는 또 다른 원숭이가 있습니다.저는 파이썬에서 객체와 클래스를 배우고 있습니다. 다른 래더 렁에서 동물의 특성을 인쇄해야하는 프로그램을 작성하려고했습니다.

원숭이는 2 개의 눈, 2 개의 손, 2 개의 다리를 가지고 있습니다. 다람쥐는 2 개의 눈과 4 개의 다리를 가지고 있습니다. 비둘기는 2 개의 눈, 2 개의 날개, 2 개의 다리를 가지고 있으며 날 수 있습니다. 독수리는 2 개의 눈, 2 개의 날개, 2 개의 다리를 가지고 있으며 날 수 있습니다.

나는

class Animal(object): 
    features= {} 

    def __init__(self,eyes,legs,hands,wings,fly): 
    self.features['eyes'] = eyes 
    self.features['legs'] = legs 
    self.features['hands'] = hands 
    self.features['wings'] = wings 
    self.features['fly'] = fly 

    def fly(self): 
    return self.features['fly'] 

class Monkey(Animal): 

    def __init__(self,eyes,legs,hands): 
    self.name = 'Monkey' 
    Animal.__init__(self,eyes,legs,hands,0,False) 

    def __repr__(self): 
    temp = {} 
    for key in self.features: 
     if(self.features[key]>0 and self.features[key]!=False): 
      temp[key] = self.features[key] 
    return str({self.name:temp}) 

class Squirrel(Animal): 

    def __init__(self,eyes,legs): 
    self.name = 'Squirrel' 
    Animal.__init__(self,eyes,legs,0,0,False)   

    def __repr__(self): 
    temp = {} 
    for key in self.features: 
     if(self.features[key]>0 or self.features[key]!=False): 
      temp[key] = self.features[key] 
    return str({self.name:temp}) 

class Pigeon(Animal): 

    def __init__(self,eyes,legs,wings): 
    self.name = 'Pigeon' 
    Animal.__init__(self,eyes,legs,0,wings,True) 

    def __repr__(self): 
    print(self.features) 
    temp = {} 
    for key in self.features: 
     if(self.features[key]>0 or self.features[key]==True): 
      temp[key] = self.features[key] 
    return str({self.name:temp}) 

class Eagle(Animal): 

    def __init__(self,eyes,legs,wings): 
    self.name = 'Eagle' 
    Animal.__init__(self,eyes,legs,0,wings,True) 

    def __repr__(self): 
    temp = {} 
    for key in self.features: 
     if(self.features[key]!=0 and self.features[key]!=False): 
      temp[key] = self.features[key] 
    return str({self.name:temp}) 

class ladder: 
    ladder_pos = {} 


    def __init__(self): 
    self.ladder_pos['3'] = Monkey(2,2,2) 
    self.ladder_pos['5'] = Squirrel(2,4) 
    self.ladder_pos['8'] = Pigeon(2,2,2) 
    self.ladder_pos['15'] = Eagle(2,2,2) 
    self.ladder_pos['17'] = Monkey(2,2,2) 

    def animal_at_rung(self,pos): 
    if(str(pos) in self.ladder_pos): 
     return self.ladder_pos[str(pos)] 
    else: 
     return ('None') 

    def get_animals_count(self): 
    return len(self.ladder_pos) 

    def hop(self,pos): 
    if(str(pos+1) in self.ladder_pos): 
     return ("Not Empty") 
    else: 
     self.ladder_pos[str(pos+1)] = self.ladder_pos[str(pos)] 
     del self.ladder_pos[str(pos)] 
     return ('None') 

내 출력

from ladderutils import ladder 

    l = ladder() 
    print (l.animal_at_rung(3)) 
    print (l.animal_at_rung(5)) 
    print (l.animal_at_rung(8)) 
    print (l.animal_at_rung(15)) 
    print (l.animal_at_rung(10)) 
    print (l.get_animals_count()) 
    print (l.animal_at_rung(3) == l.animal_at_rung(17)) 
    print (type(l.animal_at_rung(3)) == type(l.animal_at_rung(17))) 
    print (l.animal_at_rung(8).fly()) 
    print (l.animal_at_rung(3).fly()) 
    print (l.hop(3)) 
    print (l.animal_at_rung(3)) 
    print (l.animal_at_rung(4)) 
    print (l.hop(4)) 
    print (l.animal_at_rung(4)) 

ladderutils.py 동물의 특징을 인쇄하려면 두 개의 모듈 사다리 사용자 및 ladderutils

ladder-user.py 에 코드를 분리 한 is

{'Monkey': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
{'Squirrel': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
{'hands': 0, 'legs': 2, 'fly': True, 'wings': 2, 'eyes': 2} 
{'Piegon': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
{'Eagle': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
None 
4 
False 
False 
True 
True 
None 
None 
{'Monkey': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
Not Empty 
{'Monkey': {'legs': 2, 'wings': 2, 'fly': True, 'eyes': 2}} 
,210

그러나 내가 여기

Monkey <eyes: 2, legs: 2, hands: 2> 
Squirrel <eyes: 2, legs: 4> 
Pigeon <fly: True, eyes: 2, legs: 2, wings: 2> 
Eagle <fly: True, eyes: 2, legs: 2, wings: 2> 
None 
5 
False 
True 
True 
False 
None 
None 
Monkey <eyes: 2, legs: 2, hands: 2> 
Not empty 
Monkey <eyes: 2, legs: 2, hands: 2> 

답변

1

얻을 수 있겠 :

class Animal(object): 
    features= {} 

    def __init__(self,eyes,legs,hands,wings,fly): 
    self.features['eyes'] = eyes 
    self.features['legs'] = legs 
    self.features['hands'] = hands 
    self.features['wings'] = wings 
    self.features['fly'] = fly 

featuresAnimal의 모든 인스턴스 사이에 공유되는 클래스의 속성입니다. 따라서 Animal (또는의 하위 클래스)을 인스턴스화 할 때마다 이전 인스턴스에서 설정 한 값을 덮어 씁니다. 당신이 원하는 것은 인스턴스 특성을 대신 features을하는 것입니다 또한

class Animal(object): 

    def __init__(self,eyes,legs,hands,wings,fly): 
    self.features = { 
     'eyes': eyes, 
     'legs': legs, 
     'hands': hands, 
     'wings': wings, 
     'fly': fly 
     } 

각에서 __repr__ 방법 방금 Animal에서 그것을 정의 할 수있는 동안 어떤 서브 클래스를 복사 - 붙여 넣기 - 당신은 실제로 상당히 단순화 할 수 비트 :

는 몇 가지 다른 문제가 있습니다
class Animal(object): 
    def __init__(self,eyes,legs,hands,wings,fly): 
    self.features = { 
     'eyes': eyes, 
     'legs': legs, 
     'hands': hands, 
     'wings': wings, 
     'fly': fly 
     } 

    def __repr__(self): 
     temp = ", ".join(
      "{}: {}".format(k, v) 
      for k, v in self.features.items() if v 
      ) 
     return "{} <{}>".format(self.name, temp) 

- 방법은 정수를 사용하여 행동에 다음 (파이썬 명명 규칙에 따라 Ladder 이름을 지정해야합니다)를 ladder 클래스에서 다른 클래스의 속성, 문자열 키를 사용하여 ladder.ladder_pos에 argume nts로 변환하고 문자열로 변환하면 (힌트 : 정수로만 키를 사용할 수 있습니다) 등 ...하지만 코드가 예상 출력을 생성하지 못하게해서는 안됩니다.

+0

고맙습니다. 그것은 주제에 대한 나의 이해를 증가 시켰습니다. –

+0

@AjaySingh 기꺼이 도와 드리겠습니다. 그리고 문제가 해결되면 대답을 upvote 및/또는 수락하십시오.) –

관련 문제