gpt4 book ai didi

python - 是否有可能找出一个类的实例是否有一个 __dict__?

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:46 26 4
gpt4 key购买 nike

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

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