클래스는 객체지향 프로그래밍(OOP)의 기본 단위로, 데이터와 메서드(데이터를 처리하는 함수)를 묶는 청사진. 클래스를 통해 새로운 객체(인스턴스)를 생성할 수 있다.
🖥️ python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
클래스를 기반으로 생성된 객체를 인스턴스라고 한다. 각 인스턴스는 클래스의 구조를 따르지만 독립적인 값을 가질 수 있다.
🖥️ python
my_car = Car("Toyota", "Corolla") # Car 클래스의 인스턴스 생성
print(my_car.brand) # Toyota
클래스의 생성자 메서드로, 클래스가 초기화될 때 자동으로 호출된다. 주로 객체의 초기 속성을 설정하는 데 사용된다.
🖥️ python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
getter와 setter는 클래스 속성에 안전하게 접근하고 수정하기 위해 사용.
🖥️ python
class Account:
def __init__(self, balance):
self._balance = balance # _를 붙여 비공개 변수로 처리
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
account = Account(1000)
print(account.balance) # Getter 사용
account.balance = 500 # Setter 사용
한 클래스가 다른 클래스의 속성과 메서드를 물려받는 기능.
코드 재사용성과 확장성을 높이는 데 유용하다.
🖥️ python
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal): # Animal 클래스를 상속
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Woof!
클래스와 관련이 있지만, 인스턴스나 클래스 속성에 접근하지 않는 메서드. 클래스 이름을 통해 호출되며, 메서드의 동작이 독립적일 때 사용된다.
🖥️ python
class MathOperations:
@staticmethod
def add(a, b):
return a + b
print(MathOperations.add(3, 5)) # 8
클래스 자체를 첫 번째 매개변수로 받는 메서드로, 클래스 속성을 수정하거나 클래스의 동작을 정의할 때 사용한다.
🖥️ python
class MyClass:
count = 0
@classmethod
def increment_count(cls):
cls.count += 1
MyClass.increment_count()
print(MyClass.count) # 1
클래스 내부 데이터를 외부에서 직접 접근하지 못하도록 제한하고, 필요한 경우 getter와 setter를 통해 제어한다. 이를 통해 데이터의 무결성을 보장할 수 있다.
같은 이름의 메서드가 서로 다른 클래스에서 다르게 동작하도록 하는 기능입니다.
🖥️ python
class Cat(Animal):
def speak(self):
return "Meow!"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # 각각 "Woof!", "Meow!"