extend Python namedtuple with many @properties?

前端 未结 3 1673
甜味超标
甜味超标 2021-02-05 21:07

How can namedtuples be extended or subclassed with many additional @properties ?
For a few, one can just write the text below; but there are many, so I\'m looking for a gene

相关标签:
3条回答
  • 2021-02-05 21:28

    Here's one approach, a little language: turn this into Python text like the above, and exec it.
    (Expanding text-to-text is easy to do, and easy to test — you can look at the intermediate text.)
    I'm sure there are similar if not-so-little such, links please ?

    # 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
    
    0 讨论(0)
  • 2021-02-05 21:35

    How about this?

    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 讨论(0)
  • 2021-02-05 21:42

    The answer to your question

    How can namedtuples be extended or subclassed with additional @properties ?

    is: exactly the way you're doing it! What error are you getting? To see a simpler case,

    >>> class x(collections.namedtuple('y', 'a b c')):
    ...   @property
    ...   def d(self): return 23
    ... 
    >>> a=x(1, 2, 3)
    >>> a.d
    23
    >>> 
    
    0 讨论(0)
提交回复
热议问题