Inheritance & encapsulation
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
기존 클래스 확장하기
- **상속(inheritance)**은 새로운 class가 기존 class를复用할 수 있게 합니다.
- 새로운 class는 **하위クラス(subclass, child)**이고, 원본은 **상위 superclass, parent)**입니다.
class Bird(Animal):를 작성합니다 —Bird는Animal의 모든 메소드를继承합니다. (시험용 가짜코드:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
super()로 부모 호출하기
- 하위 class는
__init__에서 자체 속성을 추가할 수 있습니다. super().__init__(...)를 사용하여 먼저 부모의__init__를 실행합니다.- 이는 부모의 설정 코드를 반복하지 않도록 합니다.
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
메서드 오버라이딩
- 하위 클래스는 오버라이딩된 메서드를 가질 수 있습니다: 동일한 이름으로 정의합니다.
- 부모의 버전 대신 하위 클래스의 버전을 사용합니다.
- 이를 통해 각 클래스가 고유한 방식으로 동작할 수 있게 됩니다.
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
캡슐화
- 캡슐화란 객체의 데이터를 내부에 안전하게 보관하는 것을 의미합니다.
- Python에는 실제 'private'이 없지만, 앞부분 언더스코어(
self._balance)는 '외부에서 건드리지 마라'는 신호입니다. - 다른 코드에서는 데이터를 읽거나 변경할 때 직접 접근하지 말고 메서드를 사용해야 합니다.
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
다형성
- 다형성은 하나의 메서드 이름이 있지만, 클래스마다 다른 동작을 하는 것입니다.
- 루프는 여러 객체에 대해
.speak()을 호출해도 정확한 타입을 알 필요 없습니다. - 각 객체는 고유의 방식으로 반응합니다.
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
흔한 실수
- 하위 클래스는 부모로부터 상속받아 메서드를 추가하거나 오버라이딩할 수 있습니다.
- 데이터를_private_로 유지하고 메서드를 통해 접근하십시오(캡슐화).
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
이제 직접 해보기
- 상속, 오버라이딩, 캡슐화, 그리고 서로 다른 객체에서의 메서드 호출을 활용하십시오.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.)
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
The class Shape is given (its area returns 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns a list of each animal's speak() result, in order.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write a class Account whose __init__(self) sets a private balance self._balance to 0. Add deposit(self, amount) to add to it, and balance(self) to return it. Other code should use these methods, not touch _balance directly.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.