본문 바로가기

파이썬

Python 객체 지향 프로그래밍: 개념과 예제

반응형
Python 객체 지향 프로그래밍

Python 객체 지향 프로그래밍

소개

이번 강좌에서는 Python의 객체 지향 프로그래밍(OOP) 개념을 학습합니다. 객체 지향 프로그래밍은 프로그램을 객체 단위로 구성하여 코드의 재사용성과 유지보수성을 높이는 방법입니다.

1. 클래스와 객체

클래스 정의 및 객체 생성

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

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# 객체 생성
alice = Person("Alice", 30)
bob = Person("Bob", 25)

# 메서드 호출
alice.greet()
bob.greet()
        

2. 상속

클래스 상속

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

    def work(self):
        print(f"{self.name} is working with employee ID {self.employee_id}.")

# 객체 생성 및 메서드 호출
charlie = Employee("Charlie", 28, "E1234")
charlie.greet()
charlie.work()
        

3. 다형성

메서드 오버라이딩

class Animal:
    def sound(self):
        print("Some generic animal sound")

class Dog(Animal):
    def sound(self):
        print("Woof!")

class Cat(Animal):
    def sound(self):
        print("Meow!")

# 객체 생성 및 메서드 호출
animals = [Dog(), Cat(), Animal()]
for animal in animals:
    animal.sound()
        

4. 캡슐화

접근 제한자

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

# 객체 생성 및 메서드 호출
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
        

마무리

이번 강좌에서는 Python의 객체 지향 프로그래밍에 대해 학습했습니다. 클래스와 객체, 상속, 다형성, 캡슐화 등의 개념을 잘 이해하고 활용할 수 있도록 연습하세요.

#Python #프로그래밍 #객체지향프로그래밍 #OOP #클래스 #상속 #다형성 #캡슐화 #코딩 #Python심화