Python
[Python] 메소드 오버라이딩
jaamong
2023. 9. 8. 14:36
SpringBoot로 개발을 하다가 이번에 Python(Django)으로 개발하게 되었다. 파이썬을 공부하면서 헷갈렸던 내용을 몇 가지 정리해보려고 한다. 첫 타자는 메서드 오버라이딩!
파이썬도 다른 언어처럼 메소드 오버라이딩이 크게 다르지 않을 거라 생각했는데, 생각보다 좀 헷갈려서 정리하게 되었다.
설명보다는 코드 위주로 정리한다.
오버라이딩(Overriding)
기본적인 오버라이딩 방법이다. 부모클래스의 메서드와 동일한 이름으로 메서드를 생성한다. 아래 코드를 실행하면 인스턴스가 메서드를 호출할 때 오버라이딩한 메서드가 호출된다.
class Person:
def greeting(self):
print("hello")
class Student(Person):
def greeting(self): # Person 클래스의 greeting 메서드를 무시하고 Student 클래스에서 새로운 greeting 메서드 생성
print("hello. i am a student")
jaamong = Student()
jaamong.greeting() # hello. i am a student
중복 줄이기
super()를 사용하여 부모 클래스의 메서드를 호출하여 중복("hello")을 줄였다.
class Person:
def greeting(self):
print("hello")
class Student(Person):
def greeting(self):
super().greeting() # 부모 클래스의 메서드를 호출하여 중복 줄이기
print("i am a student")
jaamong = Student()
jaamong.greeting()
# hello
# i am a student
출처
파이썬 코딩 도장: 36.4 메서드 오버라이딩 사용하기
이번에는 파생 클래스에서 기반 클래스의 메서드를 새로 정의하는 메서드 오버라이딩에 대해 알아보겠습니다. 다음과 같이 Person의 greeting 메서드가 있는 상태에서 Student에도 greeting 메서드를 만
dojang.io