Can I overwrite the string form of a namedtuple?

前端 未结 3 1907
我寻月下人不归
我寻月下人不归 2020-12-24 05:34

For example:

>>> Spoken = namedtuple(\"Spoken\", [\"loudness\", \"pitch\"])
>>> s = Spoken(loudness=90, pitch=\'high\')
>>> str(s)         


        
3条回答
  •  自闭症患者
    2020-12-24 05:48

    Yes, it is not hard to do and there is an example for it in the namedtuple docs.

    The technique is to make a subclass that adds its own str method:

    >>> 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'
    

    Update:

    You can also used typing.NamedTuple to get the same effect.

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

提交回复
热议问题