使用许多@properties 扩展 Python 命名元组? [英] extend Python namedtuple with many @properties?
问题描述
如何使用许多额外的@properties 扩展或子类化命名元组?
对于少数人,可以只写下面的文字;但有很多,所以我正在寻找发电机或财产工厂.一种方法是从 _fields
生成文本并执行它;另一个是在运行时具有相同效果的 add_fields.
(我的@props 是获取行和字段在分散在几个表中的数据库中,所以 rec.pname
是 persontable[rec.personid].pname
;但namedtuples-with-smart-fields 也有其他用途.)
""" 用许多@properties 扩展namedtuple ? """从集合导入命名元组Person = namedtuple( "Person", "pname paddr" ) # ...人物表 = [人(史密斯",纽约"),人(琼斯",IL")]class Top( namedtuple( "Top_", "topid amount personid" )):"@财产.person ->人物表[人物ID].pname ->人名..."""__slots__ = ()@财产定义人(自己):返回个人表[self.personid]# def add_fields( self, Top.person, Person._fields ) 和这些效果一样吗?@财产def pname(self):返回 self.person.pname@财产def paddr(自我):返回 self.person.paddr# ... 还有很多rec = 顶部( 0, 42, 1 )打印 rec.person、rec.pname、rec.paddr
问题的答案
<块引用>命名元组如何扩展或使用额外的 @properties
子类化?
就是:完全按照您的方式进行!你遇到了什么错误?要查看更简单的案例,
<预><代码>>>>类 x(collections.namedtuple('y', 'a b c')):... @财产... def d(self): 返回 23...>>>a=x(1, 2, 3)>>>广告23>>>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 generator or property factory.
One way would be to generate text from _fields
and exec it;
another would be an add_fields with the same effect at runtime.
(My @props are to get rows and fields
in a database scattered across several tables,
so that rec.pname
is persontable[rec.personid].pname
;
but namedtuples-with-smart-fields would have other uses too.)
""" 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
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
>>>
这篇关于使用许多@properties 扩展 Python 命名元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!