简体   繁体   English

为什么在 Python 中创建命名元组 object 后无法读取“类型名称”

[英]Why can I not read the 'typename' after creating a namedtuple object in Python

This query is further with reference to this query此查询进一步参考此查询

So, I am trying to execute the following code:所以,我正在尝试执行以下代码:

from collections import *

tp = namedtuple('emp', 'eid enames mob')
print(tp)
print(emp)

I can execute print(tp) and the output generated is <class '__main__.emp'> .我可以执行print(tp)并且生成的 output 是<class '__main__.emp'>

But when I try to execute print(emp) , It generates the following exception:但是当我尝试执行print(emp)时,它会生成以下异常:

Traceback (most recent call last):
  File "a.py", line 5, in <module>
    print(emp)
NameError: name 'emp' is not defined

What is the reason.是什么原因。 The class emp is created. class emp已创建。 But I can not figure out how to access it directly.但我不知道如何直接访问它。 Or can I not?或者我不能?

So basically, I can create instance of tp as tp() but not instances of emp in the same way.所以基本上,我可以将 tp 的实例创建为tp tp()但不能以相同的方式创建emp的实例。 Why?为什么?

Option 1: Just repeat the type name when assigning to the returned type选项 1:在分配给返回的类型时只需重复类型名称

tp = emp = namedtuple('emp', 'eid enames mob')

Option 2 : Use a declarative style instead of the functional APIs选项 2 :使用声明式风格而不是功能性 API

from typing import NamedTuple

class emp(NamedTuple):
    eid: str
    enames: str
    mob: str

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM