본문 바로가기
Python

[Python]파이썬에서 클래스 만들기와 상속하기

by teamnova 2024. 3. 29.


파이썬은 객체 지향 프로그래밍(OOP)을 지원하는 강력한 프로그래밍 언어입니다. 클래스와 상속은 OOP의 핵심 개념으로, 코드의 재사용성, 유지 보수성, 그리고 모듈성을 높여줍니다. 이 글에서는 파이썬에서 클래스를 정의하는 방법과 클래스 상속을 사용하는 방법을 소개하겠습니다.

클래스 정의하기
클래스는 객체의 설계도와 같습니다. 이를 통해 데이터와 메서드(클래스 내의 함수)를 하나의 캡슐화된 유닛으로 묶을 수 있습니다. 파이썬에서 클래스를 정의하는 기본 구조는 다음과 같습니다

 

class ClassName:
    def __init__(self, parameters):
        # 초기화 메서드, 객체 생성 시 호출됩니다.
        self.attribute = parameters

    def method_name(self, parameters):
        # 클래스 내의 메서드 정의
        # 코드 구현


__init__ 메서드는 생성자 함수로, 객체가 생성될 때 자동으로 호출됩니다.
self는 클래스 인스턴스 자기 자신을 참조하는 변수입니다.
attribute와 method_name은 각각 클래스의 속성과 메서드입니다.

 

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        print(f"This car is a {self.brand} {self.model}.")


클래스 상속하기
상속은 기존 클래스의 모든 속성과 메서드를 새 클래스에 전달하는 메커니즘입니다. 이를 통해 기존 코드를 재사용하고 확장할 수 있습니다. 파이썬에서 클래스 상속은 다음과 같이 구현됩니다:

class BaseClass:
    # Base class code

class DerivedClass(BaseClass):
    # Derived class code, which inherits from BaseClass


BaseClass는 부모 클래스(또는 슈퍼 클래스)이며, DerivedClass는 자식 클래스(또는 서브 클래스)입니다.
자식 클래스는 부모 클래스의 모든 속성과 메서드를 상속받습니다.

class ElectricCar(Car):
    def __init__(self, brand, model, battery_size):
        super().__init__(brand, model)
        self.battery_size = battery_size

    def display_battery(self):
        print(f"This car has a {self.battery_size}-kWh battery.")


super() 함수는 부모 클래스의 __init__ 메서드를 호출하여 자식 클래스 객체를 초기화합니다.
이 예제에서 ElectricCar 클래스는 Car 클래스로부터 상속받고, 새로운 속성과 메서드를 추가하고 있습니다.