Menu
Coddy logo textTech

접근 제어자

Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 29번째.

접근 제어자는 클래스 속성과 메서드의 가시성을 제어합니다. 파이썬은 접근 제어를 위해 키워드 대신 명명 규칙을 사용합니다.

다음은 공개 접근(접두사 없음)의 예입니다:

class Person:
    def __init__(self):
        self.name = "Coddy"      # 공개 속성
        
    def greet(self):             # 공개 메서드
        return f"Hello, I'm {self.name}"

어디에서나 public 멤버에 접근할 수 있습니다:

person = Person()
print(person.name)           # Coddy
print(person.greet())        # Hello, I'm Coddy

다음은 보호된 접근(단일 언더스코어)의 예입니다:

class Employee:
    def __init__(self):
        self._salary = 50000     # 보호된 속성
    
    def _calculate_bonus(self):  # 보호된 메서드
        return self._salary * 0.1

    def show_bonus(self):
        return self._calculate_bonus()  # 클래스 내에서 사용 가능

보호된 멤버에 접근하기 (작동은 하지만 권장되지 않음):

employee = Employee()
print(employee._salary)      # 50000 - 작동은 하지만 권장되지 않음
print(employee.show_bonus()) # 5000.0 - 올바른 방법

다음은 비공개 접근(이중 밑줄)의 예입니다:

class User:
    def __init__(self):
        self.__password = "secure123"   # 비공개 속성
        
    def __encrypt(self, data):          # 비공개 메서드
        return f"Encrypted: {data}"
        
    def verify(self, input_password):
        # 클래스 내부에서 접근 가능한 비공개 멤버
        return input_password == self.__password

프라이빗 멤버를 올바르게 사용하세요:

user = User()
print(user.verify("secure123"))  # True - 퍼블릭 메서드 사용
# print(user.__password)         # AttributeError - 직접 액세스할 수 없음

출력:

Coddy
Hello, I'm Coddy
50000
5000.0
True

핵심 포인트: Python 접근 제어자는 명명 규칙입니다: 접두사 없음 = public (어디서나 접근 가능), 단일 밑줄 = protected (내부용), 이중 밑줄 = private (클래스 전용). 이러한 규칙은 명확한 경계를 설정하고 클래스 내부 요소의 실수에 의한 오용을 방지하는 데 도움이 됩니다.

challenge icon

챌린지

중급

이 챌린지에서는 포괄적인 테스트의 이점을 경험하면서 Python의 액세스 수정자(public, protected, private)를 보여주는 FileManager 클래스를 구현합니다.

TODO 주석에 따라 FileManager 클래스를 구현하도록 filemanager.py를 수정하세요. 이 파일에는 다음을 구현하기 위한 자세한 지침이 포함되어 있습니다:

  • 파일 작업을 위한 Public 메서드
  • Protected 메서드 (단일 밑줄 접두사 사용)
  • Private 메서드 (이중 밑줄 접두사 사용)
  • 캡슐화를 보여주는 메서드 간의 상호 작용

치트 시트

Python은 액세스 제어를 위해 명명 규칙을 사용합니다:

Public 액세스 (접두사 없음) - 어디서나 접근 가능:

class Person:
    def __init__(self):
        self.name = "Coddy"      # Public 속성
        
    def greet(self):             # Public 메서드
        return f"Hello, I'm {self.name}"

person = Person()
print(person.name)           # Coddy
print(person.greet())        # Hello, I'm Coddy

Protected 액세스 (단일 밑줄) - 내부용, 외부에서의 사용은 권장되지 않음:

class Employee:
    def __init__(self):
        self._salary = 50000     # Protected 속성
    
    def _calculate_bonus(self):  # Protected 메서드
        return self._salary * 0.1

employee = Employee()
print(employee._salary)      # 작동하지만 권장되지 않음

Private 액세스 (이중 밑줄) - 클래스 내부에서만 가능:

class User:
    def __init__(self):
        self.__password = "secure123"   # Private 속성
        
    def __encrypt(self, data):          # Private 메서드
        return f"Encrypted: {data}"
        
    def verify(self, input_password):
        return input_password == self.__password

user = User()
print(user.verify("secure123"))  # True - public 메서드 사용
# print(user.__password)         # AttributeError - 직접 접근할 수 없음

직접 해보기

from file_manager import FileManager

# 종합 테스트 케이스 처리기
test_case = input()

if test_case == "basic_test":
    # FileManager 인스턴스 생성
    manager = FileManager()
    # read_file 메서드 호출
    print(manager.read_file("example.txt"))
    # get_file_content 메서드 호출
    print(manager.get_file_content("example.txt"))

elif test_case == "protected_access":
    # FileManager 인스턴스 생성
    manager = FileManager()
    # 보호된(protected) 메서드 호출 시도
    # 보호된 메서드는 접근 가능하지만 내부용으로 설계됨
    print(manager._check_permissions("example.txt"))
    print("Note: Protected methods are accessible but intended for internal use only")

elif test_case == "private_access":
    # FileManager 인스턴스 생성
    manager = FileManager()
    try:
        # 비공개(private) 메서드 직접 호출 시도
        print(manager.__decrypt_content("some content"))
    except AttributeError as e:
        print(f"Error: {e}")
        print("Private methods are name-mangled and cannot be accessed directly")
    
    # 네임 맹글링(name-mangling) 형식을 사용하여 접근
    print(manager._FileManager__decrypt_content("some content"))
    print("Note: Accessed private method using name-mangled form")

elif test_case == "method_chaining":
    # FileManager 인스턴스 생성
    manager = FileManager()
    # get_file_content가 내부적으로 보호된 메서드와 비공개 메서드를 모두 호출하는 방식 시연
    print("Calling get_file_content which internally uses protected and private methods:")
    print(manager.get_file_content("example.txt"))

elif test_case == "multiple_files":
    # FileManager 인스턴스 생성
    manager = FileManager()
    # 여러 파일 처리
    files = ["document.txt", "image.jpg", "data.csv"]
    
    for file in files:
        print(f"\
Processing {file}:")
        print(manager.read_file(file))
        print(manager.get_file_content(file))

elif test_case == "name_mangling":
    # FileManager 인스턴스 생성
    manager = FileManager()
    # 네임 맹글링 시연
    print("Python's name mangling for private methods:")
    print("Attempting direct access would fail with AttributeError")
    print("Using mangled name:")
    print(manager._FileManager__decrypt_content("private data"))
    print("\
Name mangling is Python's mechanism to prevent accidental access")
    print("It renames __method to _ClassName__method internally")
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Object Oriented Programming의 모든 레슨