-
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (1)사회 2024. 9. 26. 06:00728x90반응형
상속(Inheritance)
상속은 쉽게 말해 "부모님에게 물려받는 것"이라고 생각하면 돼요.
부모님이 나에게 눈, 코, 입을 물려준 것처럼,
**상위 클래스(부모 클래스)**가 **하위 클래스(자식 클래스)**에게 속성이나 기능을 물려주는 거예요.
예를 들어, 동물을 나타내는 기본적인 틀이 있다고 해볼게요.
모든 동물은 이름이 있고, 소리를 낼 수 있죠.
이 틀을 Animal이라는 클래스로 만들 수 있어요.
그리고 이 Animal 클래스를 상속받아 각각의 동물을 만들 수 있어요.
예를 들어 강아지는 Dog 클래스, 고양이는 Cat 클래스로 만들 수 있어요.
pythonclass Animal:def __init__(self, name):self.name = namedef sound(self):pass # 나중에 각 동물마다 다르게 정의할 거예요class Dog(Animal): # Dog는 Animal에서 물려받아요def sound(self):return "멍멍"class Cat(Animal): # Cat도 Animal에서 물려받아요def sound(self):return "야옹"여기서 Dog와 Cat은 Animal이라는 부모로부터 이름이라는 속성을 물려받고,
소리 내는 방법을 각각 다르게 정의한 거예요.
pythondog = Dog("바둑이")cat = Cat("나비")print(dog.sound()) # "멍멍"print(cat.sound()) # "야옹"Dog는 "멍멍" 소리를 내고, Cat은 "야옹" 소리를 내는 거죠.
상속을 통해 공통적인 것(이름)은 물려받고,
동물마다 다른 것(소리 내기)은 각자 다르게 정의한 거예요.
728x90반응형'사회' 카테고리의 다른 글
파이썬을 배워 봅시다. 상속, 다형성, 메서드 오버라이딩, 함수에 대하여 (2) (2) 2024.09.26 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (2) (4) 2024.09.25 파이썬을 배워 봅시다. 클래스와 객체 더 깊이 살펴보기 (1) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (2) (0) 2024.09.25 파이썬을 배워 봅시다. 객체 지향 프로그래밍에 대하여 (1) (0) 2024.09.24