2010-02-03 2 views
10

명명 된 튜플을 확장하거나 서브 클래스화할 수있는 많은 추가 @properties가 있습니까?
몇 가지 경우 아래에 텍스트를 쓸 수 있습니다. 하지만 많은, 그래서 나는 발전기 또는 속성 공장을 찾고 있어요. 한 가지 방법은 _fields에서 텍스트를 생성하고 exec하는 것입니다. 다른 것은 런타임에 동일한 효과가있는 add_fields입니다.
(내 @props는 그렇게 rec.pnamepersontable[rec.personid].pname 즉, 데이터베이스에 여러 테이블에 걸쳐 흩어져 행과 필드를 얻을 수 있습니다; 하지만 namedtuples - 스마트 필드와 다른 것도 사용합니다.)많은 @properties가있는 파이썬 namedtuple을 확장합니까?

""" extend namedtuple with many @properties ? """ 
from collections import namedtuple 

Person = namedtuple("Person", "pname paddr") # ... 
persontable = [ 
    Person("Smith", "NY"), 
    Person("Jones", "IL") 
    ] 

class Top(namedtuple("Top_", "topid amount personid")): 
    """ @property 
     .person -> persontable[personid] 
     .pname -> person.pname ... 
    """ 
    __slots__ =() 
    @property 
    def person(self): 
     return persontable[self.personid] 

    # def add_fields(self, Top.person, Person._fields) with the same effect as these ? 
    @property 
    def pname(self): 
     return self.person.pname 
    @property 
    def paddr(self): 
     return self.person.paddr 
    # ... many more 

rec = Top(0, 42, 1) 
print rec.person, rec.pname, rec.paddr 
+2

당신이 당신의 자신의 질문에 대답하지 않았다? –

+0

나는 그 질문을 이해하지 못한다. 어쩌면 튜플에 속성을 표시하고 싶습니까? 원하는 경우 getitem을 덮어 씁니다. – Pepijn

+1

나는 혼란 스럽다. 당신은 당신이 요구하는 효과를 얻으려면 정확히 무엇을 해야하는 것처럼 보입니다. 무슨 문제 있니? 20 개 필드 지금 당신이 질문을 업데이트했는지 – Omnifarious

답변

13

질문

에 대한 대답은 어떻게 namedtuples 확장 할 수 있습니다 또는 추가 @properties 과 서브 클래스?

이다 : 당신이 그것을하고있는 방식 그대로! 어떤 오류가 발생하고 있습니까? 간단한 사례를 보려면

>>> class x(collections.namedtuple('y', 'a b c')): 
... @property 
... def d(self): return 23 
... 
>>> a=x(1, 2, 3) 
>>> a.d 
23 
>>> 
2

어때요? 위의 같은 파이썬 텍스트로이 설정, 그것을 간부 인 :

class Top(namedtuple("Top_", "topid amount personid")): 
    """ @property 
     .person -> persontable[personid] 
     .pname -> person.pname ... 
    """ 
    __slots__ =() 
    @property 
    def person(self): 
     return persontable[self.personid] 

    def __getattr__(self,attr): 
     if attr in Person._fields: 
      return getattr(self.person, attr) 
     raise AttributeError("no such attribute '%s'" % attr) 
0

여기에 한 가지 방법, 약간의 언어입니다.
(텍스트를 확장하는 것은 쉬운 일이며 쉽게 테스트 할 수 있습니다. — 중간 텍스트를 볼 수 있습니다.)
그렇다면 그다지 비슷하지 않은 링크가 있습니까?

# example of a little language for describing multi-table databases 3feb 
# why ? 
# less clutter, toprec.pname -> persontable[toprec.personid].pname 
# describe in one place: easier to understand, easier to change 

Top: 
    topid amount personid 
    person: persontable[self.personid] + Person 
     # toprec.person = persontable[self.personid] 
     # pname = person.pname 
     # locid = person.locid 
     # todo: chaining, toprec.city -> toprec.person.loc.city 

Person: 
    personid pname locid 
    loc: loctable[self.locid] + Loc 

Loc: 
    locid zipcode province city 
관련 문제