Skip to content Skip to sidebar Skip to footer

Can I Overwrite The String Form Of A Namedtuple?

For example: >>> Spoken = namedtuple('Spoken', ['loudness', 'pitch']) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) 'Spoken(loudness=90, pitch='hi

Solution 1:

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
>>> classSpoken(namedtuple("Spoken", ["loudness", "pitch"])):
        __slots__ = ()
        def__str__(self):
            returnstr(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

classSpoken(NamedTuple):
    
    loudness: int
    pitch: strdef__str__(self):
        returnstr(self.loudness)

Solution 2:

You can define a function for it:

defprint_loudness(self):
    returnstr(self.loudness)

and assign it to __str__:

Spoken.__str__ = print_loudness

Solution 3:

you can use code like this:

from collections import namedtuple

classSpokenTuple( namedtuple("Spoken", ["loudness", "pitch"]) ):

    def__str__(self):
        returnstr(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.

Post a Comment for "Can I Overwrite The String Form Of A Namedtuple?"