如何在python中从字典创建属性?

问题描述 投票:0回答:4

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

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)而无需明确写出所有函数?

python python-2.7 properties
4个回答
2
投票

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

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

1
投票

如果你想要一个没有任何花里胡哨的简单解决方案,我就像@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

0
投票

你可以编写一个自定义的__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'

0
投票

Some adds

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
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.