본문 바로가기
파이썬 문법

파이썬에서 클래스 핵심 개념

by mdesign 2024. 8. 12.

파이썬에서 클래스는 객체 지향 프로그래밍(OOP)에서 사용하는 핵심 개념으로, 데이터를 구조화하고 관련 기능을 그룹화하는 데 사용됩니다. 클래스는 객체를 생성하기 위한 청print으로, 객체는 클래스의 인스턴스(instance)입니다. 클래스를 사용하면 코드의 재사용성을 높이고, 복잡한 프로그램을 더 잘 조직할 수 있습니다.


1. 클래스 정의

클래스는 class 키워드를 사용하여 정의합니다. 클래스는 메서드와 속성을 포함할 수 있습니다.

class Person:
    # 클래스 변수
    species = "Homo sapiens"

    # 생성자 메서드
    def __init__(self, name, age):
        self.name = name  # 인스턴스 변수
        self.age = age    # 인스턴스 변수

    # 인스턴스 메서드
    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

    # 클래스 메서드
    @classmethod
    def get_species(cls):
        return cls.species

    # 정적 메서드
    @staticmethod
    def is_adult(age):
        return age >= 18


2. 클래스 인스턴스 생성

클래스를 정의한 후, 해당 클래스의 인스턴스를 생성할 수 있습니다.

# 인스턴스 생성
person1 = Person("Alice", 30)

# 인스턴스 메서드 호출
print(person1.greet())  # "Hello, my name is Alice and I am 30 years old."

# 클래스 메서드 호출
print(Person.get_species())  # "Homo sapiens"

# 정적 메서드 호출
print(Person.is_adult(25))  # True


3. 클래스와 인스턴스 변수

클래스 변수: 모든 인스턴스가 공유하는 변수입니다. 클래스 정의 내에서 정의됩니다.
인스턴스 변수: 각 인스턴스마다 개별적으로 가지는 변수입니다. 생성자 메서드 __init__에서 정의됩니다.

# 클래스 변수
print(Person.species)  # "Homo sapiens"

# 인스턴스 변수
print(person1.name)  # "Alice"
print(person1.age)   # 30


4. 상속

클래스는 상속을 통해 다른 클래스로부터 속성과 메서드를 물려받을 수 있습니다. 이를 통해 코드의 재사용성과 확장성을 높일 수 있습니다.

class Employee(Person):  # Person 클래스를 상속받는 Employee 클래스
    def __init__(self, name, age, employee_id):
        super().__init__(name, age)  # 부모 클래스의 생성자 호출
        self.employee_id = employee_id

    def get_employee_info(self):
        return f"Employee ID: {self.employee_id}, Name: {self.name}"

 

# 상속받은 클래스의 인스턴스 생성
emp = Employee("Bob", 28, "E12345")
print(emp.greet())            # "Hello, my name is Bob and I am 28 years old."
print(emp.get_employee_info())  # "Employee ID: E12345, Name: Bob"


5. 메서드 오버라이딩

자식 클래스에서 부모 클래스의 메서드를 재정의할 수 있습니다. 이를 메서드 오버라이딩이라고 합니다.

class Employee(Person):
    def greet(self):
        return f"Hello, I am {self.name} and I work here."

 

emp = Employee("Charlie", 35, "E67890")
print(emp.greet())  # "Hello, I am Charlie and I work here."


6. 메서드와 생성자

생성자(__init__): 객체가 생성될 때 호출되는 메서드입니다. 초기화 작업을 수행합니다.
소멸자(__del__): 객체가 소멸될 때 호출되는 메서드입니다. 자원 해제 등의 작업을 수행합니다.

class Resource:
    def __init__(self, resource_name):
        self.resource_name = resource_name
        print(f"Resource {resource_name} initialized.")

    def __del__(self):
        print(f"Resource {self.resource_name} cleaned up.")

# 인스턴스 생성
res = Resource("MyResource")
# 인스턴스가 소멸될 때 소멸자 호출
del res


7. 특수 메서드

파이썬 클래스는 특정 연산자 오버로딩을 위해 여러 특수 메서드를 제공합니다. 예를 들어, __str__, __repr__, __add__ 등이 있습니다.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)



p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)  # Point(4, 6)


8. 클래스 변수와 메서드


클래스 변수와 메서드는 클래스 이름으로 직접 접근할 수 있으며, 인스턴스를 통해서도 접근할 수 있습니다.

class MyClass:
    class_var = "Class Variable"

    @classmethod
    def class_method(cls):
        return cls.class_var

# 클래스 변수와 메서드 접근
print(MyClass.class_var)          # "Class Variable"
print(MyClass.class_method())     # "Class Variable"



이와 같이, 파이썬 클래스는 데이터와 기능을 캡슐화하고, 객체 지향 프로그래밍의 다양한 패턴과 원칙을 적용할 수 있는 강력한 도구입니다. 클래스의 개념을 잘 이해하고 활용하면 복잡한 프로그램을 더 잘 조직하고 관리할 수 있습니다.