Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以覆盖namedtuple的字符串形式吗?_Python - Fatal编程技术网

Python 我可以覆盖namedtuple的字符串形式吗?

Python 我可以覆盖namedtuple的字符串形式吗?,python,Python,例如: >>> Spoken = namedtuple("Spoken", ["loudness", "pitch"]) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) "Spoken(loudness=90, pitch='high')" 我想要的是: >>> str(s) 90 也就是说,我希望字符串表示法显示响度属性。 这可能吗?您可以为它定义一个函数: d

例如:

>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"])
>>> s = Spoken(loudness=90, pitch='high')
>>> str(s)
"Spoken(loudness=90, pitch='high')"
我想要的是:

>>> str(s)
90
也就是说,我希望字符串表示法显示响度属性。
这可能吗?

您可以为它定义一个函数:

def print_loudness(self):
    return str(self.loudness)
并将其分配给
\uuuu str\uuuu

Spoken.__str__ = print_loudness

是的,这并不难做到,而且在这本书中有一个例子

该技术是创建一个子类,添加自己的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'
更新:

你也可以用来获得同样的效果

from typing import NamedTuple

class Spoken(NamedTuple):
    
    loudness: int
    pitch: str
    
    def __str__(self):
        return str(self.loudness)

您可以使用如下代码:

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函数。

也许您应该创建一个适当的可重用类。出于好奇,这会返回一个
整数或
字符串,因为重载的
str
返回的是
int
?@Serdalis:很好,这将错误地返回一个
整数
。现在修复它。我喜欢这种方式,因为它在使用
namedtuple
的默认方式中添加了少量文本。您甚至可以使用lambda表达式来缩短它,而不会丢失太多的可读性(IMHO):
口语。(当然可以在lambda表达式中使用)。这里的用法是什么?它是必需的还是可选的?将
\uuuuu slots\uuuu
设置为空元组是一种节省内存的技术。它确保
口语
实例占用的内存量与常规元组相同。如果没有slots条目,每个实例都需要自己的字典(比元组大得多)。除了节省内存之外,值得注意的是,Python版本高达3.5.0的版本具有
\uu dict\uu
属性。因此,关于是否设置
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
属性定义的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>的决定会影响与该
属性交互的函数;e、 g.如果未设置
\uuuuuuuuuuuuuuuuuuu
,则
vars
返回
{}
,而不是
OrderedDict([('loudness',90),('pitch','high'))
。如前所述,这在Python 3.5.1中进行了更改。