객체지향 프로그래밍(Object-Oriented Programming, OOP) 은 코드를 효율적이고 재사용 가능하게 만드는 중요한 개념입니다.
이번 글에서는 OOP의 핵심 개념 중 캡슐화(Encapsulation)와 상속(Inheritance)에 대해 알아보겠습니다.
객체지향 프로그래밍(OOP)란?
객체지향 프로그래밍(OOP) 은 데이터를 객체(Object) 단위로 다루고, 각 객체가 속성(Attributes)과 메서드(Methods)를 가질 수 있도록 설계하는 프로그래밍 방식입니다.
파이썬에서 클래스(Class)를 사용하여 OOP를 구현할 수 있습니다.
📌 기본적인 클래스와 객체 예제
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"자동차 브랜드: {self.brand}, 모델: {self.model}")
my_car = Car("Hyundai", "Sonata")
my_car.display_info()
__init__() → 생성자(Constructor)
self.brand, self.model → 객체의 속성(Attribute)
display_info() → 객체의 메서드(Method)
캡슐화(Encapsulation)란?
캡슐화는 객체의 내부 데이터를 외부에서 직접 접근하지 못하도록 보호하는 개념입니다.
즉, 데이터를 숨기고 필요한 경우에만 공개하는 방식을 의미합니다.
(1) 캡슐화의 필요성
• 데이터 보호: 외부에서 직접 변수 값을 변경하는 것을 방지
• 유지보수성 향상: 내부 구현을 숨기고, 필요한 부분만 공개
• 코드 안정성 증가: 실수로 객체 데이터를 변경하는 것을 방지
(2) 파이썬에서 캡슐화 구현
🔹 1. 접근 제어자 (Public, Protected, Private)
테이블
class Person:
def __init__(self, name, age, salary):
self.name = name # public
self._age = age # protected
self.__salary = salary # private
def get_salary(self): # private 속성 접근 메서드
return self.__salary
person = Person("Alice", 30, 5000)
print(person.name) # ✅ 가능
print(person._age) # ⚠️ 가능하지만 권장되지 않음
# print(person.__salary) # ❌ 에러 발생 (private 변수 접근 불가)
print(person.get_salary()) # ✅ getter 메서드를 통해 접근
Public → 누구나 접근 가능
Protected (_변수명) → 서브클래스에서만 접근 권장
Private (__변수명) → 클래스 내부에서만 접근 가능
🔹 2. Private 속성 접근 (Getter, Setter 메서드 활용)
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private 속성
def get_balance(self): # Getter
return self.__balance
def set_balance(self, amount): # Setter
if amount >= 0:
self.__balance = amount
else:
print("잔액은 음수가 될 수 없습니다.")
account = BankAccount(1000)
print(account.get_balance()) # ✅ 1000
account.set_balance(2000) # ✅ 변경 가능
print(account.get_balance()) # ✅ 2000
account.set_balance(-500) # ❌ 오류 메시지 출력
Getter (get_메서드()) → private 속성 값을 가져옴
Setter (set_메서드()) → private 속성 값을 변경 가능하도록 만듦
상속(Inheritance)란?
상속(Inheritance) 은 기존 클래스를 재사용하여 새로운 클래스를 만들 수 있도록 하는 기능입니다.
코드 재사용성을 높이고 유지보수를 쉽게 만듦
(1) 기본 상속 구조
class Parent: # 부모 클래스
def greet(self):
print("안녕하세요! 저는 부모 클래스입니다.")
class Child(Parent): # 자식 클래스 (부모 클래스 상속)
pass
child = Child()
child.greet() # ✅ "안녕하세요! 저는 부모 클래스입니다."
자식 클래스(Child)가 부모 클래스(Parent)의 메서드를 그대로 사용 가능
(2) 상속에서 생성자 (__init__) 활용
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
print(f"안녕하세요! 저는 {self.name}입니다.")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 부모 클래스의 생성자 호출
self.age = age
def display_info(self):
print(f"이름: {self.name}, 나이: {self.age}")
child = Child("Alice", 20)
child.greet() # ✅ "안녕하세요! 저는 Alice입니다."
child.display_info() # ✅ "이름: Alice, 나이: 20"
super().__init__() → 부모 클래스의 생성자를 호출하여 속성을 초기화
(3) 메서드 오버라이딩(Method Overriding)
자식 클래스에서 부모 클래스의 메서드를 재정의(Override) 할 수 있음
class Parent:
def show(self):
print("부모 클래스 메서드")
class Child(Parent):
def show(self): # 부모 클래스의 메서드를 재정의
print("자식 클래스 메서드")
child = Child()
child.show() # ✅ "자식 클래스 메서드"
부모 클래스의 show() 메서드를 자식 클래스에서 재정의(Overriding)
4. 캡슐화 & 상속 활용 예제
은행 계좌 관리 시스템
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # private 속성
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"{amount}원이 입금되었습니다.")
else:
print("입금 금액은 0보다 커야 합니다.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"{amount}원이 출금되었습니다.")
else:
print("잔액이 부족합니다.")
def get_balance(self):
return self.__balance
class SavingsAccount(BankAccount): # BankAccount 상속
def __init__(self, owner, balance, interest_rate):
super().__init__(owner, balance)
self.interest_rate = interest_rate
def add_interest(self):
interest = self.get_balance() * self.interest_rate
self.deposit(interest)
print(f"이자 {interest}원이 추가되었습니다.")
savings = SavingsAccount("Alice", 5000, 0.02)
savings.add_interest() # ✅ 이자 추가
print(savings.get_balance()) # ✅ 최종 잔액 출력
웹 스크래핑이란? – 개념과 활용 사례 (0) | 2025.03.20 |
---|---|
파이썬 배우기: OOP 기본 – 추상화와 다형성 (0) | 2025.03.19 |
파이썬 배우기: 정규 표현식(Regex) (0) | 2025.03.12 |
파이썬 배우기: 고차 함수, 클로저 및 데코레이터 완벽 정리 (0) | 2025.03.02 |
파이썬 배우기: 재귀 함수 활용하기 (0) | 2025.02.27 |