혼공학습단/혼자 공부하는 파이썬

[혼공학습단 파이썬] #8-2. 클래스 추가 기능(프라이빗 변수, 게터와 세터, 프로퍼티, 상속)

✨️데이터분석가✨️ 2023. 8. 17. 08:00
728x90
728x90
8. 클래스
    3) 클래스 추가 기능
         (1) 프라이빗 변수
         (2) 게터와 세터
         (3) 프로퍼티
         (4) 상속

 

3) 클래스 추가 기능

 

(1) 프라이빗 변수

- 클래스 내부 변수를 외부에서 사용할 수 없는 변수

- __변수 이름

class Rect:
    def __init__(self, width, height):
        if width <= 0 or height <=0:
            raise Exception("너비와 높이는 음수가 나올 수 없습니다.")
        self.__width = width
        self.__height = height
    def area(self):
        return self.__width * self.__height

rect = Rect(10, 10)
rect.width = -10  # 프라이빗 변수로 지정되어 있어 변경되지 않음
print(rect.area())
더보기

# 실행결과

100

 

 

(2) 게터와 세터

- 값을 추출/변경하기 위해 간접적으로 속성에 접근하도록 해주는 함수

- get_변수 이름( )

  set_변수 이름( )

class Rect:
    def __init__(self, width, height):
        if width <= 0 or height <=0:
            raise Exception("너비와 높이는 음수가 나올 수 없습니다.")
        self.__width = width
        self.__height = height

    def get_width(self):
        return self.__width
    def set_width(self, width):
        if width <= 0:
            raise Exception("너비는 음수가 나올 수 없습니다.")
        self.__width = width

    def get_height(self):
        return self.__height
    def set_height(self, height):
        if height <= 0:
            raise Exception("높이는 음수가 나올 수 없습니다.")
        self.__height = height

    def area(self):
        return self.__width * self.__height

rect = Rect(10, 10)
rect.set_width(rect.get_width() + 10)
print(rect.area())
더보기

# 실행결과

200

 

 

(3) 프로퍼티

- 게터와 세터를 쉽게 사용할 수 있게 하는 기능 (데코레이터)

- @property

  @게터 함수 이름.setter

class Rect:
    def __init__(self, width, height):
        if width <= 0 or height <=0:
            raise Exception("너비와 높이는 음수가 나올 수 없습니다.")
        self.__width = width
        self.__height = height

    @property
    def width(self):
        return self.__width
    @width.setter
    def width(self, width):
        if width <= 0:
            raise Exception("너비는 음수가 나올 수 없습니다.")
        self.__width = width

    @property
    def height(self):
        return self.__height
    @height.setter
    def height(self, height):
        if height <= 0:
            raise Exception("높이는 음수가 나올 수 없습니다.")
        self.__height = height

    def area(self):
        return self.__width * self.__height

rect = Rect(10, 10)
rect.width += 10
print(rect.area())
더보기

# 실행결과

200

 

 

(4) 상속

- 어떤 클래스를 갖고 있는 기능을 물려받는 것 (= 기본 형태에 내가 원하는 형태로 일부 변형하는 것)

- 최상위 부모 클래스를 상속받아 .작성하면 많은 메소드가 나옴

- 자식 클래스는 부모 클래스를 상속받아 부모 클래스의 모든 함수/변수를 활용할 수 있음

class 부모:
    def test(self):
        print("안녕하세요")
class 자식(부모):
    pass

c = 자식()
c.test()
print(부모.mro())
print(자식.mro())
더보기

# 실행결과

안녕하세요
[<class '__main__.부모'>, <class 'object'>]
[<class '__main__.자식'>, <class '__main__.부모'>, <class 'object'>]

 

 

 

※ 파이썬 코드 학습 사이트

http://pythontutor.com 접속 → Start visualizing your code now 클릭 → 코드 작성 → Visualize Execution 클릭 → 단계별 코드 흐름 및 변수 확인 가능

 

 

 

728x90
728x90