[TIP] Class에 사전(dict)으로 property 추가하는 법

2020. 12. 18. 20:07분석 Python/구현 및 자료

728x90

 

아래 코드는 특정 값들을 바로 propert에 추가하는 코드다

kwargs에 config라는 것이 들어오면, 각각의 값들을 다 property를 해준다.

import numpy as np

def assign_config(self, kwargs):
    for key, value in kwargs.items():
        setattr(self, key, value)
    if hasattr(self, 'config'):
        # print(self.env_config)
        for key, value in self.config.items():
            # Check types based on default settings
            if hasattr(self, key):
                if type(getattr(self,key)) == np.ndarray:
                    setattr(self, key, value)
                else:
                    setattr(self, key,
                        type(getattr(self, key))(value))
            else:
                setattr(self, key, value)

kwargs에다가 다음과 같이 assign을 해주면 된다.

class Test(object) :
    def __init__(self, *args , **kwargs) :
        assign_config(self, kwargs)
    
    def test(self,) :
        return None

여기서 원하는 값은 a , b, c라는 것이 Test의 Property가 됬으면 하는 거다.

dict_ =  {"a" : 5, "b":10,"c":5}
tt =  Test(config = dict_)

또 하나 다른 꿀팁으로는 property를 프린트해주는 함수를 소개한다.

attrs = vars(tt)
print(', '.join("%s: %s" % item for item in attrs.items()))

자주 사용할 함수일 것 같아서 정리할 겸 공유한다!


 

참고

 

stackoverflow.com/questions/5969806/print-all-properties-of-a-python-class

 

Print all properties of a Python Class

I have a class Animal with several properties like: class Animal(object): def __init__(self): self.legs = 2 self.name = 'Dog' self.color= 'Spotted' self.smell= ...

stackoverflow.com

github.com/hubbs5/or-gym

 

hubbs5/or-gym

Environments for OR and RL Research. Contribute to hubbs5/or-gym development by creating an account on GitHub.

github.com

 

728x90