Notice
Recent Posts
Recent Comments
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
10-11 00:15
Archives
Today
Total
관리 메뉴

Developer_Neo

[python] 프로퍼티 본문

프로그래밍/Python

[python] 프로퍼티

_Neo_ 2022. 1. 20. 15:32
반응형

[python] 연산자 오버로딩, 정보은닉과 , __dict__

 

[python] 연산자 오버로딩, 정보은닉과 , __dict__

연산자 오버로딩 __add__(self, other) : + 연산자(A + B또는 A += B) __iadd__(self, other) : + 연산자(A += B) __sub__(self, other) : - 연산자(A - B, A -= B) __isub__(self, other) : - 연산자(A -= B) __..

devloper-dreaming.tistory.com

에서 보았듯이 정보은닉관점에서 객체가 갖는 값에 직접 접근하는 것은 오류의 확률을 높일 수 있으므로 메소드를 통해

 

접근하는 것이 안전하다고 했었다.

 

그래서 나온 메소드들은 getter와 setter인데 메소드 이름은 앞에 get, set만 붙이고 자유롭게 적는다.

 

예로 한번봐보자

class Natural:       # 자연수를 표현한 클래스
    def __init__(self, n):
        self.setn(n)       # 아래에 있는 setn 메소드 호출

    def getn(self):
        return self.__n
    
    def setn(self, n):
        if(n < 1):
            self.__n = 1
        else:
            self.__n = n

    n = property(getn, setn)


def main():
    n1 = Natural(1)
    n2 = Natural(2)
    n3 = Natural(3)
    
    n1.n = n2.n + n3.n     # n2와 n3의 덧셈 결과를 n1에 저장
    print(n1.n)
    
main()

위의 코드에서 getter와 setter를 각각 getn, setn으로 표현하였고 

 

추가적으로 n = property(getn, setn)에 대한 것을 적었다. >> 프로퍼티 설정이다.

 

만약 추가적으로 적은게 없었다면 n1.n = n2.n + n3.n 이 문장을 n1.setn(n2.getn() + n3.getn())에 해당하는 문장으로

 

적었어야 할 것이다.

 

n = property(getn, setn) 이것은

 

변수 n의 값을 참조하는 경우에 getn을 호출해서 반환되는 값을 전달

변수 n의 값을 저장하는 경우에 setn을 호출하면서 그 값을 전달

하게 되는 결과를 얻는다.

 

그래서 프로퍼티라는 것은 안정성유지, 작성하는 문장이 간결해 지는 특성을 가진다.

 

프로퍼티를 적는 방법

1.

getter setter메소드를 적은다음 밑에 get,set적용되는 변수 = property(getter메소드,setter메소드) 로 적는 법

'''
클래스 안에서 작성한다고 가정
'''

def getn(self):
	pass
    
def setn(self):
	pass
    
n=property(getn,setn)

'''
get,set적용되는 변수 = property(getter메소드,setter메소드) 형식
'''

 

2.

get,set적용되는 변수 = property() 먼저 적고 (get,set적용되는 변수= 변수 라고 칭하자) 밑에

 

getter 메소드를 적은다음 밑에 변수 = 변수.getter(getter메소드

 

setter메소드를 적은 다음 밑에 변수 = 변수.setter(setter메소드로 적는 법

'''
클래스 안에서 작성한다고 가정
'''

n = property()

def getn(self):
	pass
    
n = n.getter(getn)
    
def setn(self):
	pass
    
n = n.setter(setn)

위와 같이 프로퍼티를 등록하고 나면 getter메소드나 setter메소드를 사용할 이유가 사라진다.

 

예로 살펴보자

 

class Natural:       # 자연수를 표현한 클래스
    def __init__(self, n):
        self.setn(n)       # 아래에 있는 setn 메소드 호출

    n = property()       # property 객체 생성
    
    def getn(self):
        return self.__n
    n = n.getter(getn)       # getn을 게터로 등록
    
    def setn(self, n):
        if(n < 1):
            self.__n = 1
        else:
            self.__n = n    
    n = n.setter(setn)       # setn을 세터로 등록


def main():
    n1 = Natural(1)
    n2 = Natural(2)
    n3 = Natural(3)
    
    n1.n = n2.n + n3.n     # n2와 n3의 덧셈 결과를 n1에 저장
    print(n1.n)
    
main()

getter메소드나 setter메소드를 사용할 이유가 사라지기 떄문에 프로퍼티에 등록할 메소드의 이름(getter메소드나 setter

 

메소드 이름)을 동일하게 두기도 한다.

 

class Natural:       # 자연수를 표현한 클래스
    def __init__(self, n):
        self.n = n       # 프로퍼티 n을 통해 접근

    n = property()       # property 객체 생성
    
    def pm(self):
        return self.__n
    n = n.getter(pm)       # 위의 pm을 게터로 등록
    
    def pm(self, n):
        if(n < 1):
            self.__n = 1
        else:
            self.__n = n    
    n = n.setter(pm)       # 위의 pm을 세터로 등록


def main():
    n1 = Natural(1)
    n2 = Natural(2)
    n3 = Natural(3)
    
    n1.n = n2.n + n3.n     # n2와 n3의 덧셈 결과를 n1에 저장
    print(n1.n)
    
main()

 

 

3.

데코레이터라는 것을 기반으로 프로퍼티 등록 (@property , @변수.setter)

 

class Natural:       # 자연수를 표현한 클래스
    def __init__(self, n):
        self.n = n       # 프로퍼티 n을 통해 접근

    @property
    def n(self):
        return self.__n
    
    @n.setter    
    def n(self, n):
        if(n < 1):
            self.__n = 1
        else:
            self.__n = n


def main():
    n1 = Natural(1)
    n2 = Natural(2)
    n3 = Natural(3)
    
    n1.n = n2.n + n3.n
    print(n1.n)
    
main()

@property선언의 결과는 propery객체를 생성하면서 이어서 등장하는 메소드를 getter로 등록

 

그리고 이렇게 생성된 property객체를 메소드 이름(getter메소드 이름)인 n에 저장

 

그러면 setter는 따로 등록해야한다.

 

그래서 @n.setter 라는 것을 통해 저장하는데 n인 이유는 앞에서 property객체를 n으로 저장했기 때문이다.

 

참고한 책 : 윤성우의 열혈 파이썬 중급편

반응형
Comments