[英]How do I get the name from a named tuple in python?
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 eg 然后我可以用例如火腿访问元素
>>> 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? 如果不使用私有方法无法访问它,为什么命名元组有这种“蛋”方面?
You can get the __name__
attribute of the class: 您可以获取
__name__
属性:
>>> type(ham).__name__
'eggs'
(Here using the type()
builtin to get the class). (这里使用内置的
type()
来获取类)。
On the topic of namedtuple attributes: 关于namedtuple属性的主题:
>>> ham._fields
('x', 'y', 'z')
is sometimes useful to know 知道有时很有用
>>> ham.__class__.__name__
'eggs'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.