Can I overwrite the string form of a namedtuple?

前端 未结 3 1917
我寻月下人不归
我寻月下人不归 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:56

    you can use code like this:

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

    This will wrap namedtuple in a class of your choice which you then overload the str function too.

提交回复
热议问题