我有namedtuple
重新定义的__str__()
class MyTuple(namedtuple('MyTuple', 'field1 field2')):
__slots__ = ()
def __str__(self):
return '{}:{}'.format(self.field1, self.field2)
每次创建实例时,我都希望小写第一个字段的值,这样我就可以得到:
>>>s = MyTuple('FOO','BAR')
>>>print s
foo:BAR
而不是
FOO:BAR
在__str__()
中修改它不是我的解决方案。
答案 0 :(得分:2)
您可以覆盖__new__
静态方法并在那里应用小写:
class MyTuple(namedtuple('MyTuple', 'field1 field2')):
__slots__ = ()
def __new__(cls, field1, field2):
"""Create a new instance of MyTuple(field1, field2)"""
return super(MyTuple, cls).__new__(cls, field1.lower(), field2)
def __str__(self):
return '{}:{}'.format(self.field1, self.field2)
演示:
>>> from collections import namedtuple
>>> class MyTuple(namedtuple('MyTuple', 'field1 field2')):
... __slots__ = ()
... def __new__(cls, field1, field2):
... """Create a new instance of MyTuple(field1, field2)"""
... return super(MyTuple, cls).__new__(cls, field1.lower(), field2)
... def __str__(self):
... return '{}:{}'.format(self.field1, self.field2)
...
>>> mt = MyTuple('FOO', 'BAR')
>>> mt
MyTuple(field1='foo', field2='BAR')
>>> print(mt)
foo:BAR
>>> mt.field1
'foo'
>>> mt.field2
'BAR'