【发布时间】:2017-09-29 14:59:59
【问题描述】:
假设我有以下课程:
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' 作为其值将是我正在寻找的。p>
【问题讨论】:
-
你为什么要支持所有这些括号组合而没有括号?这种灵活性的意义何在?这对我来说似乎是一种代码味道。
-
部分原因是 to 可能被互换使用。想一想,第一种方法最合适,即
SomeConstants.PROJECT_NAME。
标签: python-3.x metaprogramming