如何在 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_NAME
、SomeConstants.PROJECT_NAME()
、SomeConstants().PROJECT_NAME
或 SomeConstants().PROJECT_NAME()
时,我都会得到相同的结果,即 ProjectConstants
的一个实例,其值为 'constants'
?
编辑
在 John Kugelman 的评论之后,我意识到调用 SomeConstants.PROJECT_NAME
并获取 ProjectConstants
的实例,并将 'constants'
作为其值将是我正在寻找的。
假设我有以下 类:
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_NAME
、SomeConstants.PROJECT_NAME()
、SomeConstants().PROJECT_NAME
或 SomeConstants().PROJECT_NAME()
时,我都会得到相同的结果,即 ProjectConstants
的一个实例,其值为 'constants'
?
编辑
在 John Kugelman 的评论之后,我意识到调用 SomeConstants.PROJECT_NAME
并获取 ProjectConstants
的实例,并将 'constants'
作为其值将是我正在寻找的。