与特定类关联的 typename 有什么用?例如,
Point = namedtuple('P', ['x', 'y'])
您通常会在哪里使用类型名“P”?
谢谢!
出于理智的考虑,namedtuple 的第一个参数应该与您分配给它的变量名称相同:
>>> from collections import namedtuple
>>> Point = namedtuple('P','x y')
>>> pp = Point(1,2)
>>> type(pp)
<class '__main__.P'>
isinstance 不太关心这一点,尽管不知道“P”是什么:
>>> isinstance(pp,Point)
True
>>> isinstance(pp,P)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'P' is not defined
但是 pickle 是一个关心找到与类型名匹配的类名的模块:
>>> import pickle
>>> ppp = pickle.dumps(pp)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python26\lib\pickle.py", line 1366, in dumps
Pickler(file, protocol).dump(obj)
File "c:\python26\lib\pickle.py", line 224, in dump
self.save(obj)
File "c:\python26\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "c:\python26\lib\pickle.py", line 401, in save_reduce
save(args)
File "c:\python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "c:\python26\lib\pickle.py", line 562, in save_tuple
save(element)
File "c:\python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "c:\python26\lib\pickle.py", line 748, in save_global
(obj, module, name))
pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P
如果我将 namedtuple 定义为“Point”,那么 pickle 很高兴:
>>> Point = namedtuple('Point','x y')
>>> pp = Point(1,2)
>>> ppp = pickle.dumps(pp)
>>>
不幸的是,由您来管理这种一致性。namedtuple 无法知道您将其输出分配给什么,因为在 Python 中分配是一个语句而不是运算符,因此您必须将正确的类名传递给 namedtuple,并将生成的类分配给相同的变量姓名。