我正在尝试使用内置的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()
时看到:这一点很重要,因为描述符不会转换为成员,
__get__
、__set__
或__delete__
表示描述符。你知道吗TL;DR
修复你的
__getattr__
,一切都应该按预期进行。你知道吗相关问题 更多 >
编程相关推荐