본문 바로가기
Python

[Python] 상속을 이용한 추가적인 기능들

by teamnova 2024. 4. 7.


파이썬에서 클래스 상속을 통해 사용할 수 있는 추가적인 기능들은 객체 지향 프로그래밍의 깊은 이해와 유연성을 제공합니다.오늘은 상속을 활용할 수 있는 몇 가지 주요 기능들을 소개합니다

 

클래스를 생성하고 상속을 하는 방법은 다음 포스팅을 참조 하세요

https://stickode.tistory.com/1147

1. 메서드 오버라이딩 (Method Overriding)
상속받은 자식 클래스에서 부모 클래스의 메서드를 재정의하여 사용할 수 있습니다. 이를 통해 자식 클래스는 상속받은 메서드의 기능을 확장하거나 변경할 수 있습니다.

class Parent:
    def greet(self):
        print("Hello from the Parent class.")

class Child(Parent):
    def greet(self):
        print("Hello from the Child class.")


2. super() 함수
super() 함수를 사용하여 부모 클래스의 메서드를 호출할 수 있습니다. 이는 메서드 오버라이딩을 할 때, 부모 클래스의 기능을 유지하면서 추가적인 기능을 구현할 때 유용합니다.

class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # 부모 클래스의 __init__ 메서드 호출
        self.age = age


3. 다중 상속 (Multiple Inheritance)
파이썬은 하나의 자식 클래스가 여러 부모 클래스로부터 상속받을 수 있는 다중 상속을 지원합니다. 이를 통해 다양한 기능을 조합하여 사용할 수 있습니다.

class Mother:
    def eye_color(self):
        return "brown"

class Father:
    def hair_color(self):
        return "black"

class Child(Mother, Father):
    pass

child = Child()
print(child.eye_color())  # "brown"
print(child.hair_color())  # "black"


4. 메서드 확장 (Extending Methods)
super() 함수를 사용하여 부모 클래스의 메서드를 호출하고, 자식 클래스에서 해당 메서드를 확장할 수 있습니다. 이는 부모 클래스의 기능은 그대로 유지하면서, 추가적인 기능을 구현하고자 할 때 사용됩니다.

class Parent:
    def greet(self):
        print("Greetings from the Parent class.")

class Child(Parent):
    def greet(self):
        super().greet()  # 부모 클래스의 greet 메서드 호출
        print("Greetings from the Child class.")


5. 다형성 (Polymorphism)
다형성은 서로 다른 클래스의 객체들이 동일한 메서드 이름을 공유하지만, 다른 행동을 할 수 있도록 하는 기능입니다. 이는 상속과 메서드 오버라이딩을 통해 구현됩니다.

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

# 다형성을 이용한 함수
def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog)  # "Woof!"
animal_sound(cat)  # "Meow!"


이러한 기능들은 파이썬의 객체 지향 프로그래밍에서 중요한 역할을 하며, 복잡한 문제를 해결하는 데 있어 유연하고 효율적인 코드 작성을 가능하게 합니다.