클래스 속성을 보호하는 방법은 무엇인가요?
접근 제한자에는 세 가지 종류가 있습니다.
public
: 어떤 클래스든 해당 속성에 접근할 수 있습니다.protected
: 해당 클래스와 동일한 클래스 또는 해당 클래스를 상속받은 클래스에서만 해당 속성에 접근할 수 있습니다.private
: 해당 클래스 내에서만 해당 속성에 접근할 수 있습니다.
이 중에서 private
접근 제한자를 사용하면 외부에서 해당 속성에 직접 접근할 수 없어 정보를 보호할 수 있습니다. 대신, public
메소드를 통해 속성에 접근하거나 수정할 수 있는 인터페이스를 제공할 수 있습니다.
아래는 Python에서 클래스 속성을 보호하는 예제 코드입니다.
class Person:
def __init__(self, name, age):
self._name = name # protected attribute
self.__age = age # private attribute
def get_name(self):
return self._name
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
person = Person('John', 25)
print(person.get_name()) # Output: John
print(person.get_age()) # Output: 25
person._name = 'Mike' # Accessing protected attribute directly
person.__age = 30 # Accessing private attribute directly
print(person.get_name()) # Output: Mike
print(person.get_age()) # Output: 25 (private attribute is not modified)
person.set_age(30)
print(person.get_age()) # Output: 30 (using public method to modify private attribute)
위의 예제 코드에서 _name
은 protected 속성으로 선언되어 외부에서 직접 접근은 가능하지만 암묵적으로 사용을 권장하지 않습니다. __age
는 private 속성으로 선언되어 외부에서 직접적인 접근은 불가능하며, get_age()
와 set_age()
메소드를 통해 속성에 접근 및 수정이 가능합니다.
클래스 속성을 보호함으로써 코드의 안정성과 유지보수성을 높일 수 있습니다.