2016-09-03 5 views
1

아마도 바보 같은 질문 일 겁니다.하지만 여기에 붙어 있습니다. 파이썬에서는 my_match.goals, my_match.yellow_cards 등과 같은 속성을 사용하여 클래스 Match를 만들었습니다. 모든 일치 항목에 동일한 속성이 있지만 게임의 전반부에만 사용하고 싶습니다. 이상적으로, 내 첫번째 생각은 하위 속성의 종류,Python : 클래스의 하위 속성

my_match.half_time.goals 

그러나 물론이 작동하지 않습니다 같은 것입니다.

내 질문은 : 그러한 필요성에 가장 적합한 데이터 구조는 무엇이고 어떻게 구현할 것입니까? 나는 서브 클래스가 좋은 생각이 아닐 것이라고 생각한다. 왜냐하면 동일한 인스턴스가 반 시간과 풀 타임을 기술 할 수 있기를 원하기 때문이다. 감사합니다.

+2

이것은 너무 광범위합니다. –

답변

1

다른 클래스를 사용하거나 작성하지 않으려면 namedtuples 개체를 사용할 수 있습니다. 명명 된 튜플 인스턴스는 변수 deferencing 또는 표준 튜플 구문과 같은 객체를 사용하여 참조 할 수 있습니다. 당신이 당신의 가치

my_match.half_time = my_match.half_time._replace(goals=10) 
+0

이것은 하나의 옵션입니다 ... 그러나 OP가 생성 후 값을 업데이트하려고 할 때 (생성시 값을 알고 있다고 가정 할 때) 구문은 매우 직관적이거나 실제 효율성이 없습니다 ... –

+0

감사합니다 당신이 완벽하게 맞는! – riccio777

1

를 업데이트하려면

from collections import namedtuple 
HalfTime = namedtuple('Halftime', 'goals yellow_cards') 
my_match.half_time = HalfTime(4, 5) 
my_match.half_time.goals 
>>> 4 
my_match.half_time.yellow_cards 
>>> 5 

은 당신이 묘사하는 것은 통계의 세트와 일치의 다른 기간에 대한 통계 별도의 세트를 유지하고있다.

별도의 통계 클래스로이를 구현하고 전체 경기에 대한 통계를 누적하는 하나의 인스턴스를 포함하여 경기의 다른 기간 동안 해당 클래스의 여러 인스턴스를 보유하게됩니다. 다음과 같은 내용 일 수 있습니다.

class Statistics(object): 
    def __init__(self): 
     self.__goals = 0 
     self.__yellow_cards =0 
    def getGoals(self): return self.__goals 
    def addGoal(self): self.__goals += 1 
    … 

class AccumulatedStatistics(object): 
    def __init__(self, *statistics): 
     self.__statistics = list(statistics) 
    def getGoals(self): 
     return reduce(lambda a,b:a.getGoals() + b.getGoals(), statistics) 
    … 

class Match(object): 
    def __init__(self): 
     self.quarterStats = [Statistics(), Statistics(), Statistics(), Statistics()] 
     self.halfStats = [ 
      AccumulatedStatistics(self.quarterStats[0], self.quarterStats[1]), 
      AccumulatedStatistics(self.quarterStats[2], self.quarterStats[3]), 
     ] 
     self.matchStats = AccumulatedStatistics(*self.quarterStats) 
+0

고마워요! 이 클래스를 단지 값을 읽는 데 사용해야하므로 'namedtuple'만으로도 충분합니다. – riccio777

관련 문제