extend Python namedtuple with many @properties?

前端 未结 3 1677
甜味超标
甜味超标 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: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)
    

提交回复
热议问题