例如:
>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"])
>>> s = Spoken(loudness=90, pitch='high')
>>> str(s)
"Spoken(loudness=90, pitch='high')"
我想要的是:
>>> str(s)
90
那就是我希望字符串表示显示响度属性。 这可能吗?
答案 0 :(得分:57)
是的,这并不难做,namedtuple docs中有一个例子。
该技术是创建一个添加自己的str方法的子类:
>>> from collections import namedtuple
>>> class Spoken(namedtuple("Spoken", ["loudness", "pitch"])):
__slots__ = ()
def __str__(self):
return str(self.loudness)
>>> s = Spoken(loudness=90, pitch='high')
>>> str(s)
'90'
答案 1 :(得分:11)
您可以为它定义一个功能:
def print_loudness(self):
return str(self.loudness)
并将其分配给__str__
:
Spoken.__str__ = print_loudness
答案 2 :(得分:4)
你可以使用这样的代码:
from collections import namedtuple
class SpokenTuple( namedtuple("Spoken", ["loudness", "pitch"]) ):
def __str__(self):
return str(self.loudness)
s = SpokenTuple(loudness=90, pitch='high')
print(str(s))
这会将namedtuple包装在您选择的类中,然后您也会重载str函数。