9. Python Programming Course : Object-Oriented Programming
9장. 객체지향 프로그래밍 (Object-Oriented Programming)
객체지향 프로그래밍(OOP)은 데이터와 동작을 하나의 단위(객체)로 묶어 설계하고 구현하는 방법론입니다. 본 장에서는 다음 다섯 가지 주제를 실습과 예제를 통해 학습합니다.
클래스(Class)와 객체(Object)
속성(Attribute)과 메서드(Method)
상속(Inheritance)
다형성(Polymorphism)
캡슐화(Encapsulation)
9.1 클래스와 객체
클래스: 객체를 생성하기 위한 설계도(템플릿)
객체: 클래스를 바탕으로 실제 메모리에 생성된 인스턴스
# 클래스 정의 예시
class Person:
def __init__(self, name, age):
self.name = name # 인스턴스 속성
self.age = age
# 객체 생성
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1.name, p1.age) # 출력: Alice 30실습 과제: Car 클래스를 정의하여 make, model, year 속성을 초기화하고, 두 개의 Car 인스턴스를 생성 후 속성 출력하기
9.2 속성과 메서드
속성(Attribute): 객체가 가지는 데이터
메서드(Method): 객체가 수행할 수 있는 함수
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.1416 * self.radius ** 2
c = Circle(5)
print(c.area()) # 출력: 78.54실습 과제: Rectangle 클래스를 만들고 width, height 속성 및 area(), perimeter() 메서드를 구현하여 테스트해보기
9.3 상속
상속(Inheritance): 기존 클래스(부모, base class)의 특성을 물려받아 새로운 클래스(자식, derived class) 생성
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
print(Dog("Buddy").speak()) # 출력: Buddy says Woof!
print(Cat("Kitty").speak()) # 출력: Kitty says Meow!실습 과제: Employee 클래스를 만들어 Person으로부터 상속받고, salary 속성 및 work() 메서드를 추가하여 인스턴스 동작 확인하기
9.4 다형성
다형성(Polymorphism): 동일한 메시지(메서드 호출)에 대해 객체별로 다른 동작을 수행하는 특성
def animal_speak(animal):
print(animal.speak())
animal_speak(Dog("Rex")) # Rex says Woof!
animal_speak(Cat("Mimi")) # Mimi says Meow!실습 과제: 이전에 만든 Employee 클래스 자식으로 Manager와 Developer 클래스를 만들고, 각각 다른 work() 동작을 구현한 뒤 다형성 확인하기
9.5 캡슐화
캡슐화(Encapsulation): 객체의 내부 상태(속성)를 직접 접근하지 못하도록 숨기고, 메서드를 통해 접근하도록 제한하는 원칙
파이썬에서는 이름 앞에 언더스코어(
_)나 이중 언더스코어(__)를 사용하여 비공개 속성(private)을 표기
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private 속성
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acct = BankAccount(1000)
acct.deposit(500)
print(acct.get_balance()) # 출력: 1500
# print(acct.__balance) # 오류 발생: private 속성 접근 불가실습 과제: Student 클래스를 정의하여 __grades 비공개 속성을 만들고, add_grade(), average() 메서드를 통해 성적을 관리하는 기능 구현하기
각 실습 과제 완료 후 코드를 리뷰하고, 클래스 설계의 장점과 객체지향 원칙을 토론해 보십시오.
댓글
댓글 쓰기