如何让一个Enum的成员进入全局命名空间? [英] How does one get an Enum's members into the global namespace?
问题描述
所以而不是:
常量(枚举):
PI = 3.14
...
area = Constant.PI * r * r
我可以说:
area = PI * r * r
有一个简单的方法从 Constant.PI
到 PI
?
正式支持的方法是这样的:
globals()。update 。$ member $)
这是因为 __成员__
该 dict
类对象,其中包含Enum类的名称和成员。
我个人觉得丑陋我通常将以下方法添加到我的枚举类中:
@classmethod
def export_to(cls,namespace):
namespace.update(cls .__ members__)
然后在我的顶级代码我可以说:
Constant.export_to(globals())
注意:将枚举导出到全局命名空间只有在模块只有一个这样的导出的枚举时才有效。如果你有几个,那么对于枚举本身来说,最好使用一个较短的别名,并使用它,而不是污染全局命名空间:
class Constant(Enum):
PI = ....
C =常量
区域= C.PI * r * r
Python now has an Enum type (new in 3.4 with PEP 435, and alse backported), and while namespaces are a good thing, sometimes Enums are used more like constants, and the enum members should live in the global (er, module) namespace.
So instead of:
Constant(Enum):
PI = 3.14
...
area = Constant.PI * r * r
I can just say:
area = PI * r * r
Is there an easy way to get from Constant.PI
to just PI
?
The officially supported method is something like this:
globals().update(Constant.__members__)
This works because __members__
is the dict
-like object that holds the names and members of the Enum class.
I personally find that ugly enough that I usually add the following method to my Enum classes:
@classmethod
def export_to(cls, namespace):
namespace.update(cls.__members__)
and then in my top level code I can say:
Constant.export_to(globals())
Note: exporting an Enum to the global namespace only works well when the module only has one such exported Enum. If you have several it is better to have a shorter alias for the Enum itself, and use that instead of polluting the global namespace:
class Constant(Enum):
PI = ....
C = Constant
area = C.PI * r * r
这篇关于如何让一个Enum的成员进入全局命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!