我试图将__dict__成员添加到由namedtuple生成的类. (__dict__出现在python 2.7.3中,但在2.7.5中删除.见http://bugs.python.org/issue15535.它存在并记录在python 3.3中.)我的代码使用vars(nametuple_object),它基于__dict__.我想在需要时补课.
这是我尝试过的:
# Applies to Python 2.7.5 +
C = namedtuple('C', ['x', 'y'])
if not hasattr(C, '__dict__'):
C.__dict__ = property(C._asdict)
这不起作用,因为C继承__dict__,因此hasattr始终为true并且(强制时)属性赋值返回:
Traceback (most recent call last):
File "namedtuple_dict.py", line 8, in
C.__dict__ = property(C._asdict)
AttributeError: attribute '__dict__' of 'type' objects is not writable
也许,有没有办法引用不继承的C成员?
解
这是我的namedtuple包装器,它使用rdb建议只继承namedtuple类而不是尝试修改它:
def namedtuple_with_dict(typename, field_names, **kwargs):
C = CBase = namedtuple(typename, field_names, **kwargs)
if 0x02070500 <= sys.hexversion < 0x03000000:
C = type(typename, (CBase,), {'__dict__': property(CBase._asdict)})
return C
解决方法:
namedtuple将__slots__设置为空元组,这是为了避免为了内存优化而创建__dict__.这意味着它的设计没有也不能有__dict__.当__slots__存在时,您无法分配__dict__或定义任何新字段.
但是,这不适用于派生类,因此您可以这样做:
CBase = namedtuple('C', ['x', 'y'])
class C(CBase):
__dict__ = property(CBase._asdict)
print C(1, 2).__dict__
标签:python,namedtuple
来源: https://codeday.me/bug/20190529/1175256.html