[Python] 클래스(Class)
1. 파이썬에서 클래스란?
클래스는 객체 지향 프로그래밍(Object-Oriented Programming, OOP) 에서 중요한 개념으로, 데이터와 그 데이터를 처리하는 방법(메서드)을 하나로 묶어주는 역할을 합니다.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
return f"This car is a {self.make} {self.model}."
2. 클래스와 객체
클래스는 객체를 생성하기 위한 템플릿이며, 객체는 클래스의 인스턴스입니다.
# 객체 생성
my_car = Car("Genesis", "G80")
# 객체의 메서드 호출
print(my_car.display_info()) # 출력: This car is a Genesis G80.
3. 생성자
생성자는 객체가 생성될 때 자동으로 호출되는 특별한 메서드입니다. 파이썬에서는 __init__
메서드가 생성자 역할을 합니다.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 생성자를 통한 객체 생성
person1 = Person("Lee", 30)
print(f"{person1.name} is {person1.age} years old.")
# 출력: Lee is 30 years old.
4. 클래스의 상속
상속은 기존 클래스의 속성과 메서드를 새로운 클래스가 재사용할 수 있게 해줍니다.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 출력: Buddy says Woof!
print(cat.speak()) # 출력: Whiskers says Meow!
5. 메서드 오버라이딩
메서드 오버라이딩은 부모 클래스의 메서드를 자식 클래스에서 재정의하는 것입니다.
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
shape = Shape()
rectangle = Rectangle(5, 3)
print(shape.area()) # 출력: 0
print(rectangle.area()) # 출력: 15
6. 클래스 변수
클래스 변수는 모든 인스턴스가 공유하는 변수입니다. 인스턴스 변수와 달리 클래스 변수는 클래스 자체에 속합니다.
class Student:
school = "Python High School" # 클래스 변수
def __init__(self, name):
self.name = name # 인스턴스 변수
student1 = Student("Lee")
student2 = Student("Kim")
print(student1.school) # 출력: Python High School
print(student2.school) # 출력: Python High School
Student.school = "Python University"
print(student1.school) # 출력: Python University
print(student2.school) # 출력: Python University
Leave a comment