I create a named tuple like this:
from collections import namedtuple spam = namedtuple('eggs', 'x, y, z') ham = spam(1,2,3)
Then I can access elements of ham with e.g.
>>> ham.x 1 >>> ham.z 3
In the interpreter,
>>> ham eggs(x=1, y=2, z=3)
But what if I just want to get 'eggs'? The only way I've been able to think of is
>>> ham.__repr__.split('(')[0] 'eggs'
but this seems a bit messy. Is there a cleaner way of doing it?
Why do named tuples have this 'eggs' aspect to them if it isn't possible to access it without resorting to a private method?
The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.
To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.
Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system.
You can get the __name__
attribute of the class:
>>> type(ham).__name__ 'eggs'
(Here using the type()
builtin to get the class).
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