クラスのクラスメソッドになるようにマジックメソッドを装飾しようとしてい__getitem__
ます。これが私が試したサンプルです。クラスメソッドまたは静的メソッドの装飾を使用してもかまいませんが、その方法がよくわかりません。これが私が試したものです:
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
前もって感謝します。