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

标签 python python-3.x class dictionary enums

我正在尝试使用内置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__ 属性和任何成员。

abc 没有出现在 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/

相关文章:

python - PyQt 5.9 中的 OpenLayers 地理定位

Python - 列表的追加和排序

java - 在类中使用私有(private)变量或公共(public)方法哪个更好?

javascript - 设置对象的单个属性

python - 我在我的 Django 模型中添加位置字段它显示错误

python - 要求从多套中各选一件的背包

python - 使用 pip 安装 pyopencv

python - 如何调整for循环的重复次数?

python - 我如何检查 python 中的 keyhold

java - 在java中导入一个类