gpt4 book ai didi

python - 如何从 python 中的命名元组中获取名称?

转载 作者:IT老高 更新时间:2023-10-28 22:25:30 24 4
gpt4 key购买 nike

我创建一个这样的命名元组:

from collections import namedtuple
spam = namedtuple('eggs', 'x, y, z')
ham = spam(1,2,3)

然后我可以使用例如访问火腿的元素

>>> ham.x
1
>>> ham.z
3

在解释器中,

>>> ham
eggs(x=1, y=2, z=3)

但如果我只想得到“鸡蛋”怎么办?我能想到的唯一方法是

>>> ham.__repr__.split('(')[0]
'eggs'

但这似乎有点困惑。有没有更清洁的方法?

如果不诉诸私有(private)方法就无法访问命名元组,为什么对它们有这种“蛋”方面?

最佳答案

可以获取类的__name__属性:

>>> type(ham).__name__
'eggs'

(这里使用 the type() builtin 来获取类)。

关于python - 如何从 python 中的命名元组中获取名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com