den*_*nis 11 python properties namedtuple
如何使用许多其他@properties对named元组进行扩展或子类化?
对于少数人,可以写下面的文字; 但是有很多,所以我正在寻找发电机或物业工厂.一种方法是从中生成文本_fields并执行它; 另一个是在运行时具有相同效果的add_fields.
(我的@props是为了让数据库中的行和字段分散在几个表中,所以rec.pname就是这样persontable[rec.personid].pname;但是,带有智能字段的namedtuples也有其他用途.)
""" 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
Run Code Online (Sandbox Code Playgroud)
Ale*_*lli 18
你的问题的答案
如何将named元组扩展或子类化
@properties?
是:你正是这样做的!你遇到了什么错误?要看一个更简单的案例,
>>> class x(collections.namedtuple('y', 'a b c')):
... @property
... def d(self): return 23
...
>>> a=x(1, 2, 3)
>>> a.d
23
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4964 次 |
| 最近记录: |