我正在尝试将魔术方法装饰__getitem__
为课堂上的类方法。这是我尝试过的示例。我不介意使用 classmethod 或 staticmethod 装饰,但我不太确定该怎么做。这是我尝试过的:
import ConfigParser
class Settings(object):
_env = None
_config = None
def __init__(self, env='dev'):
_env = env
# find the file
filePath = "C:\\temp\\app.config"
#load the file
_config = ConfigParser.ConfigParser()
_config.read(filePath)
@classmethod
def __getitem__(cls, key):
return cls._config.get(cls._env, key)
@classmethod
def loadEnv(cls, env):
cls._env = env
但是,当我尝试打电话时,Settings['database']
我收到以下错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Array[Type], got str
谁能告诉我我做错了什么。另外,有人可以建议是否有更好的方法来做到这一点?我什至尝试使用 MetaClasses,但收效甚微(因为我不太了解 python)。
class Meta(type):
def __getitem__(*args):
return type.__getitem__(*args)
class Settings(object):
__metaclass__ = Meta
提前致谢。