반응형
객체 정보 은닉
- 파이썬 클래스의 속성과 메소드 값의 접근을 제어할 수 있는 다양한 정보 은닉 기능이 있다.
- private: 해당 클래스에서만 접근 가능
- protected: 해당 클래스 또는 해당 클래스를 상속받은 클래스에서만 접근 가능
- public: 어떤 클래스라도 접근이 가능
Public
- 파이썬에서의 모든 속성과 메소드는 기본적으로 public 객체이며 별 다른 표시가 없다.
- public 객체는 클래스 내부나 외부든 어디에서나 클래스의 속성과 메소드에 접근할 수 있다.
>>> class Quadrangle:
... def __init__(self, width, height, color): # 클래스 생성자
... self.width = width
... self.height = height
... self.color = color
... def get_area(self): # public
... return self.width * self.height
... def set_area(self, width, height): # public
... self.width = width
... self.height = height
>>> square = Quadrangle(5, 5, "black") # 객체 생성
>>> print(square.get_area())
25
>>> print(square.width)
5
>>> square.width = 10
>>> print(square.get_area())
50
Protected
- 파이썬 속성 앞에 _ 언더스코어 하나만 붙여서 protected 객체를 표현한다.
- protected 키워드는 실제 제약되지는 않고 일종의 경고 표시로 사용된다.
>>> class Quadrangle:
... def __init__(self, width, height, color): # 클래스 생성자
... self._width = width
... self._height = height
... self._color = color
... def get_area(self): # public
... return self._width * self._height
... def _set_area(self, width, height): # protected
... self._width = width
... self._height = height
>>> square = Quadrangle(5, 5, "black") # 객체 생성
>>> print(square.get_area())
25
>>> print(square._width)
5
>>> square._width = 10
>>> print(square.get_area())
50
>>> square._set_area(3, 3)
>>> print(square.get_area())
9
Private
- 파이썬 속성 앞에 __ 언더스코어를 두개 붙여서 private 객체를 표현하며, 대표적으로 클래스 생성자 __init__ 가 있다.
- private 키워드는 클래스 외부에서 클래스 내부의 멤버에 접근하지 못하도록 하는 키워드로, 해당 객체에서만 private 설정된 내부 멤버에 접근이 가능하다.
- 같은 클래스에서 생성된 객체라더라도 서로 다른 객체의 private 멤버에는 접근할 수 없다.
>>> class Quadrangle:
... def __init__(self, width, height, color): # 클래스 생성자
... self.width = width
... self.height = height
... self.color = color
... def get_area(self): # public
... return self.width * self.height
... def set_area(self, width, height): # public
... self.width = width
... self.height = height
>>> square = Quadrangle(5, 5, "black") # 객체 생성
>>> dir (square)
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'color',
'get_area',
'height',
'set_area',
'width']
Reference
반응형
'Data > Python' 카테고리의 다른 글
[Python] if __name__ == "__main__"의 뜻 (0) | 2023.06.17 |
---|---|
[Python] 파이썬 모듈 - 정의, 생성 및 불러오기 (0) | 2023.06.17 |
[Python] 파이썬 클래스 - 상속과 오버라이딩, super (0) | 2023.06.17 |
[Python] 파이썬 클래스 - 변수와 메소드 (0) | 2023.06.17 |
[Python] 파이썬 클래스 - 정의 및 생성자 (0) | 2023.06.17 |