gpt4 book ai didi

python - 在 python 中使用类类型名

转载 作者:太空狗 更新时间:2023-10-29 20:14:39 24 4
gpt4 key购买 nike

与特定类关联的类型名有什么用?例如,

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,并将生成的类分配给相同的变量姓名。

关于python - 在 python 中使用类类型名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10482512/

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