RoBoLoG

[Python] 클래스와 서브클래스 본문

Study/Python

[Python] 클래스와 서브클래스

SKJun 2024. 1. 5. 10:10

클래스와 서브클래스 알아보기

 

파이썬에서 클래스와 서브클래스를 사용하는 것은 객체 지향 프로그래밍의 핵심 개념 중 하나입니다. 클래스는 객체의 청사진(blueprint)을 제공하며, 서브클래스는 부모 클래스로부터 속성과 메소드를 상속받아 확장하거나 수정할 수 있습니다.

 


다음은 파이썬에서 클래스와 서브클래스를 정의하고 사용하는 예시입니다:

기본 클래스: Vehicle

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

    def display_info(self):
        return f"Brand: {self.brand}, Model: {self.model}"

 

  • Vehicle 클래스는 차량의 기본적인 속성인 brand와 model을 가지고 있습니다.
  • __init__ 메소드는 객체가 생성될 때 자동으로 호출되어 객체의 초기 상태를 설정합니다.
  • display_info 메소드는 차량의 정보를 문자열로 반환합니다.

서브클래스: Car

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

    def display_car_info(self):
        return f"{self.display_info()}, Seats: {self.seats}"

 

  • Car 클래스는 Vehicle 클래스를 상속받습니다. 상속받은 클래스는 괄호 안에 명시됩니다.
  • super().__init__(brand, model) 호출은 부모 클래스의 __init__ 메소드를 호출하여 brand와 model 속성을 초기화합니다.
  • Car 클래스는 추가적인 속성인 seats를 가지고 있으며, 이는 차량의 좌석 수를 나타냅니다.
  • display_car_info 메소드는 부모 클래스의 display_info 메소드를 활용하여 차량 정보를 확장하여 표시합니다.

객체 생성 및 사용

vehicle = Vehicle("Toyota", "Corolla")
print(vehicle.display_info())  # Brand: Toyota, Model: Corolla

car = Car("Honda", "Civic", 5)
print(car.display_car_info())  # Brand: Honda, Model: Civic, Seats: 5

 

  • vehicle 객체는 Vehicle 클래스의 인스턴스입니다.
  • car 객체는 Car 클래스의 인스턴스이며, Vehicle 클래스의 모든 속성과 메소드를 상속받습니다.

 

이 예시에서 Car 클래스는 Vehicle 클래스의 서브클래스입니다. 서브클래스는 상속을 통해 부모 클래스의 모든 속성과 메소드를 재사용하며, 필요에 따라 새로운 속성이나 메소드를 추가하거나 기존의 것을 수정할 수 있습니다. 이렇게 함으로써 코드의 재사용성을 높이고, 유지 관리를 용이하게 합니다.

728x90
반응형