파이썬 객체지향 프로그래밍: 클래스와 객체
파이썬에서 클래스와 객체를 정의하고 사용하는 방법
객체지향 프로그래밍(Object-Oriented Programming, OOP)은 데이터를 객체로 관리하며, 코드의 재사용성과 유지보수성을 높이는 프로그래밍 패러다임입니다. 이번 글에서는 파이썬에서 클래스와 객체를 정의하고 사용하는 방법을 알아보겠습니다.
1. 객체지향 프로그래밍이란?
- 객체(Object): 데이터와 데이터를 처리하는 메서드의 묶음.
- 클래스(Class): 객체를 생성하기 위한 설계도 또는 템플릿.
- 장점:
- 코드 재사용성 증가.
- 유지보수성 향상.
- 프로그램의 구조화.
2. 클래스와 객체의 기본 구조
1) 클래스 정의
1
2
3
class 클래스이름:
# 클래스의 속성과 메서드 정의
pass
2) 객체 생성
1
2
# 클래스 인스턴스(객체) 생성
객체이름 = 클래스이름()
예제
1
2
3
4
5
6
7
8
# 클래스 정의
class Person:
def greet(self):
print("Hello, World!")
# 객체 생성 및 메서드 호출
person = Person()
person.greet() # 출력: Hello, World!
3. 생성자와 속성
1) 생성자 (__init__
메서드)
- 객체가 생성될 때 자동으로 호출되는 메서드입니다.
- 초기값을 설정하거나 객체 속성을 정의할 때 사용됩니다.
1
2
3
4
5
6
7
8
9
class Person:
def __init__(self, name, age):
self.name = name # 속성 정의
self.age = age
# 객체 생성
person = Person("Alice", 25)
print(person.name) # 출력: Alice
print(person.age) # 출력: 25
2) 속성 접근
- 속성은
self.속성명
을 통해 정의되고, 객체에서객체이름.속성명
으로 접근할 수 있습니다.
4. 메서드
클래스 내에서 정의된 함수는 메서드(Method)라고 부릅니다. 메서드는 객체와 관련된 작업을 수행합니다.
1) 인스턴스 메서드
- 객체에 속한 메서드로,
self
를 통해 객체의 속성과 메서드에 접근합니다.
1
2
3
4
5
6
7
8
9
10
11
12
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name}, and I am {self.age} years old.")
# 객체 생성 및 메서드 호출
person = Person("Bob", 30)
person.introduce()
# 출력: My name is Bob, and I am 30 years old.
2) 클래스 메서드와 정적 메서드
- 클래스 메서드 (
@classmethod
): 클래스 전체에 영향을 미치는 작업 수행. - 정적 메서드 (
@staticmethod
): 클래스나 객체와 독립적으로 동작하는 메서드.
1
2
3
4
5
6
7
8
9
10
11
class Math:
@classmethod
def square(cls, x):
return x ** 2
@staticmethod
def add(a, b):
return a + b
print(Math.square(4)) # 출력: 16
print(Math.add(2, 3)) # 출력: 5
5. 상속과 다형성
1) 상속(Inheritance)
- 기존 클래스를 기반으로 새로운 클래스를 정의하여, 코드를 재사용할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal:
def speak(self):
print("Animal makes a sound.")
class Dog(Animal): # Animal 클래스를 상속받음
def speak(self):
print("Dog barks.")
# 객체 생성
animal = Animal()
dog = Dog()
animal.speak() # 출력: Animal makes a sound.
dog.speak() # 출력: Dog barks.
2) 다형성(Polymorphism)
- 동일한 메서드 이름이 다양한 객체에서 다르게 동작할 수 있습니다.
6. 캡슐화
캡슐화(Encapsulation)는 객체의 내부 데이터를 외부에서 직접 접근하지 못하도록 보호하는 원리입니다.
파이썬에서는 속성 앞에 밑줄(_)을 붙여 비공개 속성을 나타냅니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class BankAccount:
def __init__(self, balance):
self._balance = balance # 비공개 속성
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
print("Insufficient funds")
else:
self._balance -= amount
def get_balance(self):
return self._balance
# 객체 생성 및 사용
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 출력: 150
7. 객체지향 설계의 실용 예제
1) 간단한 클래스 설계
1
2
3
4
5
6
7
8
9
10
11
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
print(f"The {self.brand} {self.model} is driving.")
car = Car("Toyota", "Camry")
car.drive()
# 출력: The Toyota Camry is driving.
2) 상속을 활용한 클래스 설계
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Vehicle:
def __init__(self, brand):
self.brand = brand
def move(self):
print(f"The {self.brand} is moving.")
class Bike(Vehicle):
def move(self):
print(f"The {self.brand} bike is pedaling.")
vehicle = Vehicle("Generic")
bike = Bike("Mountain")
vehicle.move() # 출력: The Generic is moving.
bike.move() # 출력: The Mountain bike is pedaling.
정리
- 클래스와 객체: 객체지향 프로그래밍의 기본 단위로, 데이터를 구조화하여 관리.
- 생성자와 속성: 객체 초기화와 데이터 저장.
- 상속과 다형성: 코드 재사용성과 확장성 제공.
- 캡슐화: 데이터 보호 및 은닉.
다음 글 예고:
객체지향 프로그래밍의 심화 주제로, “생성자와 소멸자, 상속과 다형성”에 대해 알아보겠습니다!
This post is licensed under CC BY 4.0 by the author.