给定一个任意类X
作为输入,是否可以找出X
的实例是否具有__dict__
?
我尝试了 hasattr(X, '__dict__')
,但这不起作用,因为它检查类对象是否具有 __dict__
:
>>> hasattr(int, '__dict__')
True
>>> vars(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
缺少__slots__
也不能保证存在__dict__
:
>>> hasattr(int, '__slots__')
False
>>> vars(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
我还考虑过使用 object.__new__(X)
创建 X
的实例(以绕过 X.__new__
和 X .__init__
,这可能会产生不需要的副作用),但这对于内置类型会失败:
>>> hasattr(object.__new__(int), '__dict__')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object.__new__(int) is not safe, use int.__new__()
是否可以在不调用任何未知/不受信任的代码(例如 X
的构造函数)的情况下执行此操作?
最佳答案
dir()
将列出 Python3 中的 __dict__
,例如:
>>> class MyInt(int):
... pass
...
>>> '__dict__' in dir(int)
False
>>> '__dict__' in dir(MyInt)
True
>>>
关于python - 是否有可能找出一个类的实例是否有 __dict__ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789322/