python

8편 Python 객체지향 프로그래밍 (OOP) 기초

파이썬 티쳐 2024. 11. 13. 21:25

1. 클래스와 객체

1.1 객체지향 프로그래밍이란 무엇인가

객체지향 프로그래밍(Object-Oriented Programming, OOP)은 현실 세계의 개념을 프로그래밍으로 표현하는 방식입니다. 프로그램을 데이터와 그 데이터를 처리하는 방법(메서드)을 포함한 객체들로 구성하여 문제를 해결합니다. OOP의 핵심 개념은 캡슐화, 상속, 다형성, 추상화입니다.

1.2 클래스와 객체의 기본 개념

  • 클래스(Class): 객체를 생성하기 위한 설계도입니다. 속성(데이터)과 메서드(행동)을 정의합니다.
  • 객체(Object): 클래스를 바탕으로 생성된 실체로, 클래스의 인스턴스(instance)입니다.
class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Buddy")  # 'Dog' 클래스의 인스턴스인 객체 'my_dog' 생성

1.3 클래스 정의와 객체 생성

클래스를 정의하기 위해 class 키워드를 사용합니다. 클래스를 정의한 후, 이를 이용해 객체를 생성할 수 있습니다.

class Car:
    def __init__(self, model, color):
        self.model = model
        self.color = color

# 'Car' 클래스의 객체 생성
my_car = Car("Tesla", "Red")

1.4 속성(변수)과 메서드(함수)의 정의

클래스는 속성(변수)과 메서드(함수)를 가집니다.

  • 속성: 객체의 데이터를 저장하는 변수로, 객체마다 고유한 값을 가질 수 있습니다.
  • 메서드: 객체가 수행할 행동을 정의하는 함수입니다.
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
    
    def speak(self):
        print(f"{self.name} says hello!")

# 객체 생성
dog = Animal("Buddy", "Dog")
dog.speak()  # 출력: Buddy says hello!

2. 생성자와 소멸자

2.1 생성자 메서드 (__init__)의 역할과 사용법

생성자 메서드는 객체가 생성될 때 자동으로 호출되며, 객체의 속성을 초기화하는 역할을 합니다. 생성자는 __init__ 메서드를 사용하여 정의됩니다.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 객체 생성
person = Person("Alice", 25)
print(person.name)  # 출력: Alice

2.2 객체가 소멸될 때 호출되는 소멸자 (__del__) 소개

소멸자(__del__)는 객체가 삭제되거나 프로그램이 종료될 때 호출됩니다. 보통 자원을 해제하거나 종료 메시지를 출력할 때 사용됩니다.

class Sample:
    def __del__(self):
        print("객체가 소멸되었습니다.")

sample = Sample()
del sample  # 출력: 객체가 소멸되었습니다.

2.3 생성자를 활용한 객체 초기화 예제

생성자를 통해 객체의 초기 상태를 설정할 수 있습니다.

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def display_info(self):
        print(f"'{self.title}' by {self.author}")

# 객체 생성 및 초기화
book = Book("1984", "George Orwell")
book.display_info()  # 출력: '1984' by George Orwell

3. 클래스와 객체의 활용

3.1 간단한 클래스 예제: 학생 클래스

학생의 이름과 성적을 저장하고 출력하는 간단한 클래스를 작성할 수 있습니다.

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def display_info(self):
        print(f"학생 이름: {self.name}, 성적: {self.grade}")

# 객체 생성
student = Student("Bob", "A+")
student.display_info()  # 출력: 학생 이름: Bob, 성적: A+

3.2 객체 간의 상호작용 예제

객체는 서로 상호작용할 수 있습니다. 예를 들어, 학생과 수업 객체가 상호작용하는 프로그램을 작성할 수 있습니다.

class Course:
    def __init__(self, name):
        self.name = name
        self.students = []

    def add_student(self, student):
        self.students.append(student)

    def show_students(self):
        print(f"{self.name} 수업의 학생들:")
        for student in self.students:
            print(f"- {student.name}")

class Student:
    def __init__(self, name):
        self.name = name

# 객체 생성 및 상호작용
math = Course("수학")
alice = Student("Alice")
bob = Student("Bob")

math.add_student(alice)
math.add_student(bob)
math.show_students()
# 출력:
# 수학 수업의 학생들:
# - Alice
# - Bob

3.3 클래스와 객체를 활용한 실제 프로그램 예제: 쇼핑몰 주문 관리 시스템

쇼핑몰에서 상품을 주문하고, 주문 내역을 관리하는 시스템을 만들어봅니다.

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

class Order:
    def __init__(self):
        self.items = []

    def add_product(self, product, quantity):
        self.items.append((product, quantity))

    def total_price(self):
        total = sum(product.price * quantity for product, quantity in self.items)
        return total

    def show_order(self):
        print("주문 내역:")
        for product, quantity in self.items:
            print(f"{product.name} - {quantity}개")
        print(f"총 가격: {self.total_price()}원")

# 객체 생성 및 주문 관리
apple = Product("Apple", 1000)
banana = Product("Banana", 1500)

order = Order()
order.add_product(apple, 3)
order.add_product(banana, 2)
order.show_order()
# 출력:
# 주문 내역:
# Apple - 3개
# Banana - 2개
# 총 가격: 6000원