Python 객체지향 프로그래밍 마스터하기: 클래스, 상속, 캡슐화, 다형성
Python 객체지향 프로그래밍
이 가이드는 Python 객체지향 프로그래밍(OOP)의 핵심 개념을 실용적 예제와 함께 안내하며, 견고하고 재사용 가능한 코드 작성법을 보여줍니다.
동영상: Python 객체지향 프로그래밍
객체지향 프로그래밍
Python은 여러 프로그래밍 스타일을 지원하는 멀티 패러다임 언어. 가장 강력한 접근법 중 하나는 객체를 사용해 문제를 모델링하는 것—객체지향 프로그래밍(OOP)입니다.
객체는 두 가지 필수 특성을 가집니다:
- 속성(Attributes, 데이터)
- 행동(Behavior, 메서드)
예를 들어 앵무새는 name, age, color 같은 속성과 sing(), dance() 같은 행동을 가진 객체입니다.
Python OOP는 DRY(Don't Repeat Yourself) 원칙을 따르며 재사용 가능한 코드를 촉진합니다.
클래스
class는 객체의 구조와 행동을 정의하는 청사진(blueprint). 앵무새의 상세 스케치라 생각하면 됩니다: 어떤 속성과 행동을 가질지 명시.
class Parrot:
pass
여기서 Parrot은 빈 클래스. 이 클래스의 인스턴스는 나중에 생성.
객체
객체(또는 인스턴스)는 클래스의 구체적 실체. 클래스 정의 시 메모리 할당 안 되고 템플릿만 존재. 클래스 인스턴스화로 객체 생성.
obj = Parrot()
아래 예에선 기능적 Parrot 클래스를 만들고 blu, woo 두 인스턴스 생성:
class Parrot:
# 클래스 속성
species = "bird"
# 인스턴스 속성
def __init__(self, name, age):
self.name = name
self.age = age
# 클래스 인스턴스화
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# 클래스 속성 접근
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# 인스턴스 속성 접근
print("{} is {} years old".format(blu.name, blu.age))
print("{} is {} years old".format(woo.name, woo.age))
출력
Blu is a bird Woo is also a bird Blu is 10 years old Woo is 15 years old
이 스니펫에서 species는 모든 앵무새가 공유하는 클래스 속성, name과 age는 각 객체 고유의 인스턴스 속성.
메서드
메서드는 클래스 내 정의된 함수로 객체 행동을 설명. 클래스 인스턴스에서 호출.
class Parrot:
def __init__(self, name, age):
self.name = name
self.age = age
def sing(self, song):
return f"{self.name} sings {song}"
def dance(self):
return f"{self.name} is now dancing"
# 인스턴스화 및 메서드 사용
blu = Parrot("Blu", 10)
print(blu.sing("'Happy'"))
print(blu.dance())
출력
Blu sings 'Happy' Blu is now dancing
상속
상속으로 새 클래스가 기존 클래스의 속성/메서드 물려받아 코드 재사용과 논리적 계층 구축.
# 베이스 클래스
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# 파생 클래스
class Penguin(Bird):
def __init__(self):
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
출력
Bird is ready Penguin is ready Penguin Swim faster Run faster
캡슐화
캡슐화는 객체 내부 상태에 직접 접근 제한해 데이터 무결성 보호. Python에선 언더스코어 접두사(단일/이중)로 비공개 속성 표시.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print(f"Selling Price: {self.__maxprice}")
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# 직접 수정 시도
c.__maxprice = 1000
c.sell()
# 세터 메서드 사용
c.setMaxPrice(1000)
c.sell()
출력
Selling Price: 900 Selling Price: 900 Selling Price: 1000
다형성
다형성은 서로 다른 클래스의 객체를 공통 인터페이스로 다룰 수 있게 해 다양한 객체 타입에서 작동하는 유연한 코드 작성 가능.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# 공통 인터페이스
def flying_test(bird):
bird.fly()
blu = Parrot()
peggy = Penguin()
flying_test(blu)
flying_test(peggy)
출력
Parrot can fly Penguin can't fly
핵심 요약
- OOP는 코드를 명확하고 유지보수하기 쉽게 구조화.
- 클래스로 상속을 통한 코드 재사용 가능.
- 캡슐화로 내부 데이터 보호.
- 다형성으로 객체 타입 간 유연한 인터페이스 제공.