-
[inheritance] 상속 with 예제🐍 파이썬/파이썬 기본 문법 2022. 7. 28. 12:08
In OOP languages, classes can extend existing classes to inherit their behavior. At the same time, they can changeand extendthe behavior.
*reminder : A class is an abstraction and represents a consistent combination of state(instance variables or “fields”) and operations to alter this state (“methods”).
Lets start with the class represents "Animal" which has age and food state, and next_day, feed, is_alive, make_noise methods
there is a unified diagram to represent class : unified modeling language (UML)
Now, let's create concrete animal classes (cat, dog) that inherit above Animal class
OOP languages support Polymorphism so make_noise is dynamically “dispatched”.
It can be decided at the runtime of a program, depending on the type of the receiver object, which implementation of a specific method needs to be invoked.
But It does not make sense to instantiate Animal, how can we prevent it?
=> abstraction base class!
An abstract base class can provide functionality that is relevant for subclasses without being constructable(cannot be instantiated). Define abstract methods in an abstract base class to indicate that subclasses must implement a particular method (template methods).
Private : __food is only visible from within the class and subclasses
Protected : _hunger is only visible from within the class and subclasses in the same module - in Python only by convention!
Public : make_noise is visible to any other class
Let’s Implement Kangaroos ! it has baby in pouch
'🐍 파이썬 > 파이썬 기본 문법' 카테고리의 다른 글
[inheritance] Multiple Inheritance (0) 2022.07.29 [OOP] The Four Core Principles of OOP (0) 2022.07.28 [class] python-specific special method (0) 2022.07.27 [OOP] class 클래스 개념 및 구성요소 (0) 2022.07.27 [list] reference and copy (aliasing and clone) (0) 2022.07.19