有没有可能找出一个类的实例是否有一个dict?

2024-06-01 14:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个任意类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.__new__X.__init__创建一个X实例,这可能会产生不想要的副作用),但对于内置类型来说,这是失败的:

>>> 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的构造函数)的情况下做到这一点?你知道吗


Tags: inmostnewstdinlinevarscalldict
2条回答

您可以使用^{}模块获取实例的所有非方法属性

>>> import inspect
>>> from operator import itemgetter

>>> b = 5
>>> inspect.getmembers(b, lambda a:not(inspect.isroutine(a)))

将生成b的所有属性及其小描述的长列表。你知道吗

我做了一些测试,看看它是如何工作的,下面是我的发现

>>> def get_attrs(x):
       return list(map(itemgetter(0), inspect.getmembers(x, lambda a:not(inspect.isroutine(a)))))

>>> "__dict__" in get_attrs(type(b))
>>> False

>>> l = [1,2,3]
>>> "__dict__" in get_attr(type(l))
>>> False

>>> class A:
       pass

>>> a = A()
>>> "__dict__" in get_attr(type(a))
>>> True

dir()将在Python3中列出__dict__,示例:

>>> class MyInt(int):
...     pass
...
>>> '__dict__' in dir(int)
False
>>> '__dict__' in dir(MyInt)
True
>>>

相关问题 更多 >