Skip to main content
 首页 » 编程设计

python : ENUM class elements are not reachable for built-in dir() function

2024年09月03日32jackei

我正在尝试使用内置的 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__ 的存在表示描述符.


长话短说

修复你的 __getattr__,一切都应该按预期工作。