【问题标题】:How to create properties from a dictionary in python?如何从python中的字典创建属性?
【发布时间】:2017-12-16 01:00:15
【问题描述】:

我有一本包含一些基本设置的字典,例如:

config = {'version': 1.0,
          'name': 'test'
          }

使用这个配置,我想像这样设置一个类:

class Foo:
    def __init__(self):
        self._version = config['version']
        self._name = config['name']

    @property
    def version(self):
        return self._version
    @property
    def name(self):
        return self._name

有没有一种方法可以创建这些属性(使用漂亮的自动 getter+setter)而无需显式写出所有函数?

【问题讨论】:

  • 您需要属性而不是简单的实例属性是否有特殊原因?如果没有,你可以做 self.__dict__.update(config).

标签: python python-2.7 properties


【解决方案1】:

如果你让你的类继承自dict这是可能的

class PropDict(dict):
    __getattr__= dict.__getitem__
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

【讨论】:

  • 这是一个非常有趣和聪明的解决这个问题的方法......我第一次看到它。我不确定我是喜欢它还是认为它对我的口味来说可能有点太神奇了。
【解决方案2】:

如果您想要一个没有任何花里胡哨的简单解决方案,我的想法与@PaulPanzer 相同:

class Config:
    def __init__(self, config):
        self.__dict__.update(config)

    # If you want to keep other attributes from getting set
    def __setattr__(self, key, value):
        if key not in self.__dict__:
            raise AttributeError(key)
        self.__dict__[key] = value

【讨论】:

    【解决方案3】:

    你可以写一个自定义的__getattr__方法:

    config = {'version': 1.0,
          'name': 'test'
          }
    class Foo:
       def __init__(self):
          self._version = config['version']
          self._name = config['name']
       def __getattr__(self, name):
          data = [b for a, b in self.__dict__.items() if a[1:] == name]
          if not data:
              raise AttributeError('{} not found'.format(name))
          return data[0]
    

    输出:

    f = Foo()
    print(f.name)
    

    输出:

    'test'
    

    【讨论】:

      【解决方案4】:

      一些补充

      config = {'version': 1.0,
                'name': 'test',
                'date': "18/12/2018"
                }
      
      
      class Config:
         def __init__(self, config):
            'creates the object'
            self.__dict__.update(config)
      
         def add(self, k, v):
            'adds a key with a value'
            self.__dict__[k] = v
      
         def list(self):
            'shows all the keys'
            for k in self.__dict__.keys():
               print(k)
      
      >>> f = Config(config)
      >>> f.list()
      version
      name
      date
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2014-03-03
        • 1970-01-01
        • 2020-01-20
        • 2021-06-25
        • 2016-03-08
        • 2010-12-10
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多