0Pricing
Python For Kids · 강의

캡슐화

고급 객체 지향 프로그래밍 개념을 살펴봅니다.

캡슐화은(는) CoddyKit의 무료 Python For Kids 강의입니다. 이것은 5개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python For Kids 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python For Kids 강의에는 총 5개의 강의가 포함되어 있습니다.

캡슐화

객체 지향 프로그래밍(OOP) 수업에 다시 오신 것을 환영합니다! 오늘은 클래스 내부의 데이터와 메서드를 보호하는 데 도움이 되는 핵심 개념인 Python의 캡슐화에 대해 알아보겠습니다.

캡슐화 — 일러스트레이션 1

캡슐화란?

캡슐화는 데이터(속성)와 해당 데이터를 처리하는 메서드(함수)를 클래스라는 하나의 단위 안에 묶는 개념입니다. 또한 객체의 일부 구성 요소에 직접 접근하지 못하도록 제한하여 객체의 내부 표현을 외부에 숨깁니다.

  • 데이터 은닉: 객체의 내부 상태를 의도하지 않은 간섭으로부터 보호합니다.
  • 접근 제어: 데이터와 메서드에 접근하거나 이를 수정하는 방법을 정의합니다.

캡슐화를 사용하면 객체가 자신의 데이터를 제어하고 필요한 항목만 외부에 공개할 수 있습니다.

접근 제어자

Python에서는 접근 제어자를 사용하여 클래스 구성원(속성과 메서드)의 공개 범위를 제어함으로써 캡슐화를 구현합니다. 접근 제어자에는 세 가지 유형이 있습니다.

  • 공개: 어디에서나 접근할 수 있습니다.
  • 보호: 클래스와 해당 하위 클래스 내부에서 접근할 수 있습니다.
  • 비공개: 클래스 자체의 내부에서만 접근할 수 있습니다.

Python에서 이러한 접근 제어자를 사용하는 방법을 살펴보겠습니다.

공개 속성과 메서드

공개 구성원은 클래스 외부에서도 접근할 수 있습니다. 별도로 지정하지 않으면 모든 속성과 메서드는 기본적으로 공개됩니다.

예시:

# Defines the Person class with public attributes and methods
class Person:
    def __init__(self, name, age):
        self.name = name  # Public attribute
        self.age = age    # Public attribute

    def greet(self):
        print("Hello, my name is " + self.name + "!")  # Public method

# Creates an object of the Person class
person1 = Person("Alice", 30)

# Accesses public attributes and methods
print(person1.name)  # Output: Alice
person1.greet()      # Output: Hello, my name is Alice!

보호된 속성과 메서드

보호된 구성원은 앞에 밑줄 하나(_)를 붙여 표시합니다. 클래스와 해당 하위 클래스 내부에서 접근할 수 있지만 클래스 외부에서 직접 접근해서는 안 됩니다.

예시:

# Defines the Employee class with protected attributes and methods
class Employee:
    def __init__(self, name, salary):
        self._name = name      # Protected attribute
        self._salary = salary  # Protected attribute

    def _increase_salary(self, amount):
        self._salary += amount  # Protected method
        print(self._name + "'s new salary is " + str(self._salary))

# Creates an object of the Employee class
employee1 = Employee("Bob", 50000)

# Accesses protected attributes and methods (not recommended)
print(employee1._name)  # Output: Bob
employee1._increase_salary(5000)  # Output: Bob's new salary is 55000

비공개 속성과 메서드

비공개 구성원은 앞에 밑줄 두 개(__)를 붙여 표시합니다. 클래스 자체의 내부에서만 접근할 수 있으며 클래스 외부에서는 직접 접근할 수 없습니다.

예시:

# Defines the BankAccount class with private attributes and methods
class BankAccount:
    def __init__(self, owner, balance):
        self.__owner = owner    # Private attribute
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount  # Modifies private attribute
        print("Deposited:", amount)
        self.__show_balance()

    def __show_balance(self):
        print("Current Balance:", self.__balance)  # Private method

# Creates an object of the BankAccount class
account1 = BankAccount("Charlie", 1000)

# Attempts to access private attributes and methods (will cause errors)
# print(account1.__owner)        # AttributeError
# account1.__show_balance()      # AttributeError

# Uses public methods to interact with private attributes
account1.deposit(500)  # Output:
                        # Deposited: 500
                        # Current Balance: 1500

캡슐화를 사용하는 이유

캡슐화는 여러 가지 장점을 제공합니다.

  • 제어: 데이터에 접근하거나 데이터를 수정하는 방법을 제어할 수 있습니다.
  • 보안: 객체의 내부 상태를 의도하지 않은 변경으로부터 보호합니다.
  • 유지 관리 용이성: 코드를 더 쉽게 유지 관리할 수 있고 오류가 발생할 가능성도 줄어듭니다.

캡슐화는 견고하고 안전한 애플리케이션을 만드는 데 도움이 됩니다.

캡슐화 예제: Car 클래스

attributes와 methods를 보호하는 캡슐화를 사용하는 Car 클래스를 만들어 보겠습니다.

코드:

# Defines the Car class with encapsulated attributes and methods
class Car:
    def __init__(self, make, model, year):
        self.make = make          # Public attribute
        self.model = model        # Public attribute
        self.__year = year        # Private attribute

    def get_year(self):
        return self.__year  # Public method to access private attribute

    def set_year(self, year):
        if year > 0:
            self.__year = year  # Public method to modify private attribute
            print("Year updated to", self.__year)
        else:
            print("Invalid year!")

    def __display_info(self):
        print(self.make, self.model, self.__year)  # Private method

    def show_info(self):
        self.__display_info()  # Public method that calls a private method

# Creates an object of the Car class
car1 = Car("Tesla", "Model S", 2020)

# Accesses public attributes and methods
print(car1.make)        # Output: Tesla
print(car1.get_year())  # Output: 2020

# Modifies the private attribute using a public method
car1.set_year(2021)     # Output: Year updated to 2021

# Calls a public method that interacts with a private method
car1.show_info()        # Output: Tesla Model S 2021

# Attempts to access private attributes and methods directly (will cause errors)
# print(car1.__year)         # AttributeError
# car1.__display_info()      # AttributeError
# Defines the Student class with encapsulated attributes
class Student:
    def __init__(self, name, grade):
        self.name = name      # Public attribute
        self.__grade = grade  # Private attribute

    def get_grade(self):
        return self.__grade  # Public method to access private attribute

    def set_grade(self, grade):
        if 0 <= grade <= 100:
            self.__grade = grade  # Updates the grade
        else:
            print("Invalid grade!")

# Creates an object of the Student class
student1 = Student("Diana", 85)

# Accesses and modifies the grade using public methods
print(student1.get_grade())  # Output: 85
student1.set_grade(90)
print(student1.get_grade())  # Output: 90

# Attempts to access the private attribute directly (will cause an error)
# print(student1.__grade)     # AttributeError

잘하셨습니다!

Python에서 캡슐화를 사용하여 클래스 내부의 데이터와 methods를 보호하는 방법을 학습하셨습니다. 캡슐화를 사용하면 객체 데이터에 대한 접근을 제어할 수 있으므로 프로그램의 보안성과 유지 관리성이 향상됩니다. 적절한 접근 제어자를 사용하여 클래스를 설계하면서 계속 연습해 코딩 실력을 높여 보세요!

캡슐화 — 일러스트레이션 10

자주 묻는 질문

“캡슐화” 강의는 무료인가요?

네 — “캡슐화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python For Kids 강의 전체를 잠금 해제할 수 있습니다. Python For Kids 강의에는 총 5개의 강의가 포함되어 있습니다.

“캡슐화”에서 뭘 배우나요?

고급 객체 지향 프로그래밍 개념을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Python For Kids을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Python For Kids을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Python For Kids은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 5개 중 4번째 강의입니다.

“캡슐화” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Python For Kids 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Python For Kids 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 객체 지향 프로그래밍 소개
  2. 클래스와 객체 만들기
  3. 상속
  4. 캡슐화
  5. 다형성
← Python For Kids(으)로 돌아가기