如何在 Python 3 中将变量赋值转换为方法调用?

How may I turn a variable assignment into a methodcall in Python 3?

假设我有以下 类:

class Constants():
    def __init__(self, constant=None):
        self.value = constant
    # Some magic goes here

class SomeConstants(Constants):
    PROJECT_NAME = 'constants'

如何以编程方式将该定义转换为

class SomeConstants(Constants):
    @staticmethod
    def PROJECT_NAME():
        return SomeConstants('constants')

这样每当我调用 SomeConstants.PROJECT_NAMESomeConstants.PROJECT_NAME()SomeConstants().PROJECT_NAMESomeConstants().PROJECT_NAME() 时,我都会得到相同的结果,即 ProjectConstants 的一个实例,其值为 'constants'

编辑 在 John Kugelman 的评论之后,我意识到调用 SomeConstants.PROJECT_NAME 并获取 ProjectConstants 的实例,并将 'constants' 作为其值将是我正在寻找的。

神奇的方法call()可能就是您要找的。

Python中的Enumclass如我所愿。 使用枚举,需要做一些细微的改动,但就我的意图和目的而言,它解决了问题。