2017-12-16 7 views
0

나는 다음과 같은 몇 가지 기본 설정으로 사전이이 설정을 사용하여사전에서 파이썬으로 속성을 만드는 방법은 무엇입니까?

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로) 명시 적으로 모든 함수를 작성할 필요없이?

+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 
>>> 
관련 문제