gpt4 book ai didi

python - python中namedtuple中的字段小写

转载 作者:行者123 更新时间:2023-12-01 04:37:54 25 4
gpt4 key购买 nike

我有这个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__() 中修改它对于我来说不是一个解决方案。

最佳答案

您可以重写__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'

关于python - python中namedtuple中的字段小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31407186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com