본문 바로가기

python & django & scipy

[python] @property, __init__

 

먼저, __new__ 메소드와 __init__ 메소드의 차이를 알아보려한다. 

파이썬은 항상 __new__ 가 __init__ 보다 먼저 호출된다. 

__new__는 인스턴스 객체를 메모리에 할당하고 object를 반환한다. 

__init__은 인스턴스를 생성하는 것이 아니고 생성된 인스턴스의 멤버 변수를 초기화하고 필요에 따라 자원을 할당한다.

__new__의 첫번째 인자에는 cls(클래스)가 들어가고 __init__의 첫번째 인자에는 self(인스턴스)가 들어간다.

 

 

파이썬에서는 @property를 사용하면 getter와 setter를 일반 필드로 바로 접근하는 것처럼 사용할 수 있다. 

 

class MyClass:
    @property
    def title(self):
    	return self._title
    
    @title.setter
    def title(self, title):
        self._title = title

실행 예시)

>>>> myInstance = MyClass()
>>>> myInstance.title = 'this is title'
>>>> print(myInstance.title)
'this is title'

 

 

따라서 __init__ 시에 초기화한 변수를 @property를 통해 쉽게 접근할 수 있게된다.

 

class MyClass:
    def __init__(self, title=None):
    	if title is not None:
            self._title = title

    @property
    def title(self):
    	return self._title
>>>> myInstance = MyClass('this is title')
>>>> myInstance.title
'this is title'

바로 위에서는 setter를 따로 두지 않고 init에서 변수를 초기화 시킨다.

나는 웬만하면 변경할 일이 없는 property의 경우 이런식으로 선언해서 사용한다.