给定一个任意类 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
>>>
