마법 메서드 __getitem__
을 클래스의 클래스 메서드로 꾸미려고합니다. 다음은 내가 시도한 샘플입니다. 나는 classmethod 나 staticmethod 데코레이션을 사용하는 것에 신경 쓰지 않는다. 그러나 나는 그것을하는 방법을 너무 확신하지 못한다. 여기에 내가 뭘하려 : 그러나마법 메서드의 @StaticMethod 또는 @ClassMethod 장식
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를 사용해 보았지만, 거의 성공하지 못했습니다 (파이썬도 잘 모름).
class Meta(type):
def __getitem__(*args):
return type.__getitem__(*args)
class Settings(object):
__metaclass__ = Meta
미리 감사드립니다.
관련되지 않음,하지만 당신은 self._env'과'자기'에 할당 잊고 있습니다. 당신의'__init__' 메소드에서'_config'를 사용하십시오. 클래스 레벨의 속성'_env'와'_config'도 쓸모가 없습니다. –