2017-12-16 21 views
0

私のようないくつかの基本的な設定で辞書があります。Pythonで辞書からプロパティを作成するには?

この設定を使用して
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 

は、これらのプロパティを作成する方法はあります(素晴らしい自動ゲッター+セッターで)明示的にすべての関数を書く必要はありませんか?

+3

を追加し、あなたが必要とする特定の理由があります単純なインスタンス属性とは対照的にプロパティ?そうでない場合は、自己__ dict __。update(config)を実行できます。 –

答えて

2

あなたはあなたがカスタム__getattr__方法書くことができますdict

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

これはこの問題の本当に面白くて巧妙な解決策です...初めて見ました。私はそれを愛しているか、それが私の味のためにやや魔法のように思えるかどうかは分からない。 –

0

からクラスを継承を行う場合、これは可能です:

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' 
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

一部は

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 
>>> 
関連する問題