英文:
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:
>>> type('', (), {})
<class '__main__.'>
Is there any issue that might arise from doing it?
答案1
得分: 2
以下是您要翻译的部分:
这里有一件事情无法正常工作:pickle。
这个示例可以正常工作,因为它具有有效的类名标识符:
>>> Good = type('Good', (), {})
>>> setattr(__main__, 'Good', Good)
>>> good = Good()
>>> pickle.loads(pickle.dumps(good))
<__main__.Good object at 0x7ff0d8173160>
这个示例无法正常工作,因为类名为空:
>>> Bad = type('', (), {})
>>> setattr(__main__, '', Bad)
>>> bad = Bad()
>>> pickle.loads(pickle.dumps(bad))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_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:
>>> Good = type('Good', (), {})
>>> setattr(__main__, 'Good', Good)
>>> good = Good()
>>> pickle.loads(pickle.dumps(good))
<__main__.Good object at 0x7ff0d8173160>
This does not work, because the class name is empty:
>>> Bad = type('', (), {})
>>> setattr(__main__, '', Bad)
>>> bad = Bad()
>>> pickle.loads(pickle.dumps(bad))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_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 '' or '77'. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论