Python/포스팅

파이썬 메서드 오버라이딩

짜집퍼박사(짜박) 2023. 12. 3. 03:10

메서드 오버라이딩(Method Overriding)은 파이썬과 같은 객체 지향 프로그래밍 언어에서 자식 클래스가 부모 클래스로부터 상속받은 메서드를 동일한 이름의 메서드로 다시 정의하는 것을 말합니다. 이렇게 하면 자식 클래스에서 부모 클래스의 메서드를 덮어쓸 수 있습니다.

메서드 오버라이딩을 통해 자식 클래스는 부모 클래스의 동일한 이름의 메서드를 사용하지만, 자신만의 동작을 구현할 수 있습니다. 이것은 객체 지향 프로그래밍의 다형성(polymorphism)의 한 예로 볼 수 있습니다.

 

기본적인 메서드 오버라이딩

class ParentClass:
    def greeting(self):
        print("Hello from ParentClass")

class ChildClass(ParentClass):
    # 부모 클래스의 greeting 메서드를 오버라이딩
    def greeting(self):
        print("Hello from ChildClass")

# ChildClass의 객체 생성
child_obj = ChildClass()

# 오버라이딩된 메서드 호출
child_obj.greeting()  # 출력: Hello from ChildClass

 

super() 함수 사용

super() 함수를 사용하여 자식 클래스에서 부모 클래스의 메서드를 호출할 수 있습니다. 이를 통해 부모 클래스의 메서드를 오버라이딩하면서도 부모 클래스의 동작을 유지할 수 있습니다.

class ParentClass:
    def greeting(self):
        print("Hello from ParentClass")

class ChildClass(ParentClass):
    def greeting(self):
        # 부모 클래스의 greeting 메서드 호출
        super().greeting()
        print("Hello from ChildClass")

# ChildClass의 객체 생성
child_obj = ChildClass()

# 오버라이딩된 메서드 호출
child_obj.greeting()

 

부모 클래스 메서드와 자식 클래스 메서드 동시 사용

자식 클래스에서 메서드를 오버라이딩하더라도 부모 클래스의 메서드를 여전히 사용하고 싶을 때, super() 함수를 활용합니다.

class ParentClass:
    def greeting(self):
        print("Hello from ParentClass")

class ChildClass(ParentClass):
    def greeting(self):
        # 부모 클래스의 greeting 메서드 호출
        super().greeting()
        print("Hello from ChildClass")

    def child_specific_method(self):
        print("This is a method specific to ChildClass")

# ChildClass의 객체 생성
child_obj = ChildClass()

# 오버라이딩된 메서드 호출
child_obj.greeting()

# 부모 클래스의 메서드와 자식 클래스의 메서드 모두 호출
child_obj.child_specific_method()

메서드 오버라이딩은 코드를 보다 유연하게 만들어주며, 다형성의 개념을 구현할 수 있습니다. 부모 클래스의 메서드를 자식 클래스에서 필요에 따라 수정하여 사용하면서도, 필요하다면 super() 함수를 사용하여 부모 클래스의 메서드를 호출할 수 있습니다.

 

With ChatGPT

'Python > 포스팅' 카테고리의 다른 글

파이썬 모듈 생성  (0) 2023.12.03
파이썬 클래스 변수  (0) 2023.12.03
파이썬 클래스 상속  (0) 2023.12.03
파이썬 생성자  (0) 2023.12.03
파이썬 객체  (0) 2023.12.03