For example:
>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"]) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) "Spoken(loudness=90, pitch='high')"
What I want is:
>>> str(s) 90
That is I want the string representation to display the loudness attribute. Is this possible ?
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.
A Python namedtuple is Immutable Like its regular counterpart, a python namedtuple is immutable. We can't change its attributes. To prove this, we'll try changing one of the attributes of a tuple of type 'Colors'.
Namedtuples are immutable objects, so you cannot change the attribute values.
As namedtuples are a subclass of tuples, the fields can be accessed via the index or by the name of the field. The index value of a field is tied to the order during the declaration of the namedtuple. Consider the above Address example. You can access the street field by name or by using 0 as the index value.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With