使用type创建一个空名称的类

huangapple go评论62阅读模式
英文:

Making a class with empty name using type

问题

根据Python的内置函数type的文档:

class type(name, bases, dict, **kwds)

[...]

有三个参数时,返回一个新的类型对象。这本质上是class语句的一种动态形式。_name_字符串是类名,并成为__name__属性。

我已经意识到_name_字符串也可以为空,函数调用仍然有效:

>>> type('', (), {})
<class '__main__.'>

这样做可能会导致什么问题吗?

英文:

According to Python's documentation for the built-in function type:

> class type(name, bases, dict, **kwds)
>
> [...]
>
> With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute.

I have realized that the name string might as well be empty, and the function invocation would still work:

&gt;&gt;&gt; type(&#39;&#39;, (), {})
&lt;class &#39;__main__.&#39;&gt;

Is there any issue that might arise from doing it?

答案1

得分: 2

以下是您要翻译的部分:

这里有一件事情无法正常工作:pickle

这个示例可以正常工作,因为它具有有效的类名标识符:

&gt;&gt;&gt; Good = type('Good', (), {})
&gt;&gt;&gt; setattr(__main__, 'Good', Good)
&gt;&gt;&gt; good = Good()
&gt;&gt;&gt; pickle.loads(pickle.dumps(good))
<__main__.Good object at 0x7ff0d8173160>

这个示例无法正常工作,因为类名为空:

&gt;&gt;&gt; Bad = type('', (), {})
&gt;&gt;&gt; setattr(__main__, '', Bad)
&gt;&gt;&gt; bad = Bad()
&gt;&gt;&gt; pickle.loads(pickle.dumps(bad))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
_pickle.UnpicklingError: pickle data was truncated

我确信还有其他可能遇到问题的地方。使用“正常”的方式定义类型不允许类名为'''77'。任何函数都可以假定如此。

当使用type创建新类型时,应确保遵循相同的限制,而不是假设库会处理无效标识符,就好像它们是有效的。

英文:

Here is one thing which won't work correctly: pickle.

This works, because it has a valid identifier for class name:

&gt;&gt;&gt; Good = type(&#39;Good&#39;, (), {})
&gt;&gt;&gt; setattr(__main__, &#39;Good&#39;, Good)
&gt;&gt;&gt; good = Good()
&gt;&gt;&gt; pickle.loads(pickle.dumps(good))
&lt;__main__.Good object at 0x7ff0d8173160&gt;

This does not work, because the class name is empty:

&gt;&gt;&gt; Bad = type(&#39;&#39;, (), {})
&gt;&gt;&gt; setattr(__main__, &#39;&#39;, Bad)
&gt;&gt;&gt; bad = Bad()
&gt;&gt;&gt; pickle.loads(pickle.dumps(bad))
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
_pickle.UnpicklingError: pickle data was truncated

I am sure there are other places where one could encounter problems. Using the "normal" way to define types does not allow class names like &#39;&#39; or &#39;77&#39;. It is correct for any function to assume that.

When using type to create a new type, one should make sure that the same restrictions are followed, instead of assuming that libraries are going to handle invalid identifiers as if they were valid.

huangapple
  • 本文由 发表于 2023年4月20日 00:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定