-
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (2)사회 2024. 9. 26. 07:00728x90반응형
다형성(Polymorphism)
다형성은 같은 동작을 하는 것처럼 보여도,
누구(어떤 객체)가 하느냐에 따라 다르게 행동하는 것을 말해요.
예를 들어 "소리 내기"라는 동작은 강아지와 고양이 모두 할 수 있어요.
하지만 강아지는 "멍멍", 고양이는 "야옹" 소리를 내죠. 이게 바로 다형성이에요.
pythondef make_sound(animal):print(animal.sound())make_sound(dog) # "멍멍"make_sound(cat) # "야옹"make_sound라는 함수는 동물이 누구인지 상관없이 소리 내기 동작을 시키는데,
결과는 동물에 따라 달라지죠. 이게 다형성입니다.
같은 동작(소리 내기)이라도 각 동물마다 다른 방식으로 실행되는 거예요.
메서드 오버라이딩(Method Overriding)
메서드 오버라이딩은 쉽게 말해서 "부모님이 물려준 방법을 내가 다시 정의하는 것"이에요.
부모님이 가르쳐준 방법도 있지만, 나는 내 방식대로 하고 싶을 때,
상속받은 메서드를 내가 원하는 방식으로 바꿀 수 있어요.
pythonclass Bird(Animal):def sound(self):return "짹짹"이제 Bird는 Animal 클래스를 상속받았지만,
sound라는 메서드를 새롭게 정의했어요.
즉, 부모님이 물려준 방식 대신 자신의 방식으로 소리를 내는 거예요.
super() 함수
super()는 상속받은 부모님의 방법을 가져다 쓰고 싶을 때 사용하는 거예요.
부모님이 물려준 기능을 살짝만 더하거나 확장하고 싶을 때 사용해요.
pythonclass Person:def __init__(self, name, age):self.name = nameself.age = ageclass Student(Person):def __init__(self, name, age, student_id):super().__init__(name, age) # 부모님이 물려준 초기화 방법 사용self.student_id = student_idStudent는 부모님(Person)이 물려준 이름과 나이를 그대로 사용하면서,
자신만의 학번도 추가로 설정할 수 있어요. 부모님의 기능을 가져와서 확장한 거죠.
정리
상속은 부모님에게 물려받는 것처럼,
상위 클래스가 하위 클래스에게 속성과 기능을 물려주는 거예요.
다형성은 같은 행동을 하더라도,
누가 하느냐에 따라 다르게 동작하는 것을 의미하고,
메서드 오버라이딩은 부모님의 방식을 내가 새롭게 정의하는 거예요.
super()는 부모님의 방법을 그대로 사용하면서,
거기에 내가 필요한 것을 덧붙이는 기능입니다.
728x90반응형'사회' 카테고리의 다른 글
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (1) (0) 2024.09.26 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (2) (4) 2024.09.25 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (1) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (2) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (1) (0) 2024.09.24