小编Bob*_*pra的帖子

魔术方法上的@StaticMethod或@ClassMethod装饰

我试图将魔术方法装饰__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
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试调用时,Settings['database']我收到以下错误.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Array[Type], got str
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么.此外,有人可以建议是否有更好的方法来做到这一点?我甚至尝试过使用MetaClasses,但收效甚微(因为我不太了解python).

 class Meta(type):
  def __getitem__(*args):
   return type.__getitem__(*args)

 class Settings(object):
  __metaclass__ = Meta
Run Code Online (Sandbox Code Playgroud)

提前致谢.

python static-methods decorator magic-methods

1
推荐指数
1
解决办法
1527
查看次数

标签 统计

decorator ×1

magic-methods ×1

python ×1

static-methods ×1