python - 从枚举中获取所有值,当值在 Python 3.7 中是可调用的

标签 python enums python-3.7 member function-call

我有一个 Enum Python 3.7 中的类定义如下:

# activation functions
def relu(x: float) -> float:
    return x * (x > 0)


def sigmoid(x: float) -> float:
    return 1 / (1 + math.exp(-x))


class Activation(Enum):
    SIGMOID = sigmoid
    RELU = relu

    def __call__(self, x):
        return self.value(x)

    @classmethod
    def values(cls):
        return [function.value for function in cls]

我在网上尝试了其他类似问题的一些方法,例如 list(Activation)Activation.values()但总是得到一个空列表。有什么新想法吗?

最佳答案

如果您使用 aenum 1 个库,您可以使用它的 member描述符:

from aenum import Enum, member

class Activation(Enum):

    SIGMOID = member(sigmoid)
    RELU = member(relu)

    def __call__(self, x):
        return self.value(x)

    @classmethod
    def values(cls):
        return [function.value for function in cls]

也可以写成:
class Activation(Enum):

    @member
    def SIGMOID(x: float) -> float:
        return 1 / (1 + math.exp(-x))

    @member
    def RELU(x: float) -> float:
        return x * (x > 0)

    def __call__(self, x):
        return self.value(x)

    @classmethod
    def values(cls):
        return [function.value for function in cls]

1 披露:我是 Python stdlib Enum 的作者, enum34 backport ,以及 Advanced Enumeration ( aenum )图书馆。

关于python - 从枚举中获取所有值,当值在 Python 3.7 中是可调用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61578617/

相关文章:

python - 深度列表计数 - 列表中的列表计数

c# - 如何使用枚举从描述中获取值

python - 类里面的外部词典阅读行为

python - Windows:如何配置多个版本的Python以协同工作?

python - 在 Python 中为我的日期添加 1 天

Python kivy md 导航栏放置?

enums - 在 Kotlin 中,当枚举类实现接口(interface)时,如何解决继承的声明冲突?

c++ - 检查 C++11 枚举类的总顺序(如何实现 operator<)

python - 如何使用 requirements.txt 中的 pip 和 setup.py 安装 github zip 文件?

python - theano g++ 未检测到