이것 저것 개발 공부/Python
[Python] 상속과 다형성
crushed-taro
2025. 2. 3. 17:20
728x90
반응형
1. 상속(Inheritance)이란
상속은 기존 클래스(부모 클래스)의 속성과 메서드를 새로운 클래스(자식 클래스)가 물려받아 사용하는 것을 의미합니다.
상속을 활용하면 코드 중복을 줄이고, 유지보수가 쉬워집니다.
- Child 클래스는 Parent 클래스를 상속받아 greet() 메서드를 사용할 수 있습니다.
- 자식 클래스에서 별도로 정의하지 않아도 부모 클래스의 기능을 그대로 가져옵니다.
class Parent:
def greet(self):
print("안녕하세요, 저는 부모 클래스입니다!")
class Child(Parent):
pass
child = Child()
child.greet() # 안녕하세요, 저는 부모 클래스입니다!
2. 메서드 오버라이딩(Method Overriding)
자식 클래스가 부모 클래스의 메서드를 재정의(Overriding)할 수도 있습니다. 이걸 통해 클래스마다 다른 동작을 정의할 수 있습니다.
- Child 클래스에서 greet(0 메서드를 새롭게 정의했기 때문에 부모 클래스의 메서드 대신 자식 클래스의 메서드가 호출됩니다.
- 이처럼 부모 클래스의 메서드를 덮어쓰는 것을 오버라이딩이라고 합니다.
class Parent:
def greet(self):
print("안녕하세요, 저는 부모 클래스입니다!")
class Child(Parent):
def greet(self):
print("안녕하세요, 저는 자식 클래스입니다!")
child = Child()
child.greet() # 출력: 안녕하세요, 저는 자식 클래스입니다!
3. super()로 부모 클래스 접근하기
자식 클래스에서 부모 클래스의 메서드를 호출하고 싶을 때는 super() 키워드를 사용합니다.
- super().greet()를 통해 부모 클래스의 메서드를 호출한 후, 자식 클래스의 추가 동작을 수행했습니다.
- 이 방식은 부모 클래스의 기능을 확장할 때 유용합니다.
class Parent:
def greet(self):
print("안녕하세요, 저는 부모 클래스입니다!")
class Child(Parent):
def greet(self):
super().greet() # 안녕하세요, 저는 부모 클래스입니다!
print("안녕하세요, 저는 자식 클래스입니다!")
child = Child()
child.greet() # 안녕하세요, 저는 자식 클래스입니다!
4. 다형성(Polymorphism)
다형성은 하나의 인터페이스가 여러 형태로 동작할 수 있게 하는 개념입니다. 쉽게 말해, 같은 메서드가 다른 클래스에서 다른게 동작하도록 만드는 것입니다.
- Dog와 Cat 클래스는 각각 sound() 메서드를 다르게 구현했습니다.
- 반복문에서 animal.sound()를 호출할 때, 객체에 따라 다른 결과가 출력됩니다.
- 같은 메서드가 객체에 따라 다르게 동작하는 것이 다형성입니다.
class Animal:
def sound(self):
print("동물이 소리를 냅니다.")
class Dog(Animal):
def sound(self):
print("멍멍!")
class Cat(Animal):
def sound(self):
print("야옹!")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
###
멍멍!
야옹!
###
5. 계산기 프로그램
class Calculator:
def calculate(self, a, b):
pass # 기본 동작 정의 X
class Adder(Calculator):
def calculate(self, a, b):
return a + b
class Subtractor(Calculator):
def calculate(self, a, b):
return a - b
class Multiplier(Calculator):
def calculate(self, a, b):
return a * b
class Divider(Calculator):
def calculate(self, a, b):
if b != 0:
return a / b
else:
return "0으로 나눌 수 없습니다."
calculators = [Adder(), Subtractor(), Multiplier(), Divider()]
a, b = 10, 5
for calc in calculators:
print(calc.calculate(a, b))
728x90
반응형