我正在尝试使用内置dir获取ENUM类变量。 对于普通类,我们得到以下结果,
from enum import Enum
class foo(Enum):
a = 1
b = 2
c = 3
>>> dir(foo)
['__class__', '__doc__', '__members__', '__module__', 'a', 'b', 'c']
但是如果我稍微调整这个类以使用点运算符获取字典值,如下所示,
class foo(Enum):
class DotDict(dict):
# Use this to access the dictionary elements using dot notation
def __getattr__(*args):
val = dict.get(*args)
return DotDict(val) if type(val) is dict else val
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
# class variables
a = DotDict({'index': 1, 'city': {'name': 'NY', 'len': 2}})
b = DotDict({'index': 2, 'city': {'name': 'London', 'len': 6}})
c = DotDict({'index': 3, 'city': {'name': 'Delhi', 'len': 5}})
我得到以下结果,不包含类变量,
>>> dir(foo)
['DotDict', '__class__', '__doc__', '__members__', '__module__']
这里有一件奇怪的事情是我仍然可以访问如下所示的类变量,
>>> foo.a.index
1
>>> foo.b.city.name
London
我不知道类对象无法访问类变量的确切原因。有什么方法可以像使用内置的 dir 一样获取上述类的类变量的完整列表吗?
最佳答案
在早期的 3.x 行中,dir()
可以作为类上的 __dir__
方法来实现,并且 Enum
利用了这一点其中仅显示四个 __xxx__
属性和任何成员。
a
、b
和 c
没有出现在 dir(foo)
中的原因是因为它们不是成员,而且它们不是成员是因为 DotDict.__getattr__()
已损坏。
对于缺少属性,__getattr__
的适当响应是引发 AttributeError
,但您的返回的是 DotDict
实例和搜索名称,添加 print()
后可以看出:
>>> a.__get__
({'a': 1}, '__get__')
这很重要,因为描述符不会转换为成员,并且 __get__
、__set__
或 __delete__
的存在表示描述符.
TL;DR
修复你的__getattr__
,一切都应该按预期工作。
关于 python : ENUM class elements are not reachable for built-in dir() function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56561060/