枚举方式Enums [英] Pythonic way around Enums

查看:299
本文介绍了枚举方式Enums的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是pythonic 方式告诉函数调用者给定参数支持哪些值?

What is the pythonic way to tell the caller of a function what values a given parameter supports?

他是PyQt的一个例子(用于GUI)。说我有一个复选框,

He is an example for PyQt (for GUI). Say I have a checkbox,

class checkbox(object):
    ....
    def setCheckState(self, value):
        ....

这里, setCheckState()只能期望 未选中

PyQt使用内置枚举(即 Qt.Checked Qt.Unchecked ),但这是可怕的。我正在文档中寻找与我正在使用的对象的枚举。

PyQt uses a built-in enumeration (i.e. Qt.Checked or Qt.Unchecked), but this is awful. I am constantly in the documentation looking for the enum for the object I am working with.

显然,PyQt是用一个不起眼的 C ++语言编写的。这个或者类似的问题在Python中如何处理?根据 PEP 435 ,枚举似乎是最近添加的语言,对于非常具体的应用程序,所以我假设有/有更好的方法来处理这个问题?

Obviously PyQt is written in an unpythonic C++ sytle. How should this or a similar problem be handled in Python? According to PEP 435, enums seem to be a recent addition to the language and for very specific applications, so I would assume there is/was a better way to handle this?

我想让我写的代码易于使用,当我的功能需要具体参数值 - 几乎像函数的组合框。

I want to make the code I write easy to use when my functions require specific parameter values--almost like a combobox for functions.

推荐答案

一个明显的方式是函数注释。

class CheckBox(enum.Enum):
    Off = 0
    On = 1

def setCheckState(self, value: CheckBox):
    ...

这很清楚,应该是一个 CheckBox 的实例。使用枚举只是让这更容易。

This says quite clearly that value should be an instance of CheckBox. Having Enum just makes that a bit easier.

虽然2.7中没有直接支持注释本身。常见的解决方法包括将信息放在函数doc字符串(各种工具可以找到它)中或在注释中(如我们已经知道的那样)。

Annotations themselves aren't directly supported in 2.7, though. Common workarounds include putting that information in the function doc string (where various tools can find it) or in comments (as we already knew).

如果寻找一种方法你自己的代码:使用注释装饰器。这具有在3 +中继续工作的优点:

If looking for a method for your own code: use an annotating decorator. This has the advantage of continuing to work in 3+:

class annotate(object):
    def __init__(self, **kwds):
        self.kwds = kwds
    def __call__(self, func):
        func.__annotations__ = self.kwds

@annotate(value=CheckBox)
def setCheckState(self, value):
    ...

要成为一个强大的装饰器,它应该检查 kwds 的内容是否与函数参数名称匹配。

To be a robust decorator it should check that the contents of kwds matches the function parameter names.

这篇关于枚举方式Enums的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆