반응형
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 파일 입출력과 예외 처리 (0) | 2024.06.12 |
|---|---|
| "Python 자료구조 심화 (2) | 2024.06.08 |
| Python 제어문과 반복문 심화 (0) | 2024.06.08 |
| Python 기초 프로그래밍: 첫걸음을 위한 가이드 (2) | 2024.06.08 |