728x90
다형성이란 여러가지 형태를 가질 수 있는 능력을 말한다.
파이썬에는 뭐 형식의 다형성, 메서드 다형성이 있다고들 하는데, 나는 그냥 함수의 인자로 서로 다른 인스턴스를 받아 다른 결과를 도출하거나, 서로 다른 인스턴스의 메서드를 호출하는 것이라고 말하고 싶다.
가장 주요 사항은 "서로 다른 인스턴스" 이다.
다형성은 어떤 인스턴스를 적용하냐에 따라 각각 결과값이 달라지는 것이라고 생각하면 되겠다.
아래는 예시 코드이다.
# 다형성 실습
class Product:
price = 0
bonusPoint = 0
# 매개변수가 있는 생성자
def __init__(self, price):
self.price = price
self.bonusPoint = int(self.price / 10.0)
class Tv(Product):
def __init__(self,price):
# 조상클래스의 생성자 호출
super().__init__(price)
def __str__(self):
return "TV"
class Computer(Product):
def __init__(self,price):
# 조상클래스의 생성자 호출
super().__init__(price)
def __str__(self):
return "Computer"
class Audio(Product):
def __init__(self,price):
# 조상클래스의 생성자 호출
super().__init__(price)
def __str__(self):
return "Audio"
class Buyer:
money = 1000
bonusPoint = 0
def buy(self,product):
# buyer의 돈이 부족한 경우
if self.money < product.price:
print("잔액이 부족하여 물건 구입이 안됩니다.")
return
self.money -= product.price << 다형성
self.bonusPoint += product.bonusPoint << 다형성
print(product.__str__()+" 를 구매하였습니다.") << 다형성
print("잔액 : ", self.money)
print("보너스 보인트 : ", self.bonusPoint)
buyer = Buyer()
tv = Tv(100)
audio = Audio(50)
computer = Computer(2000)
buyer.buy(tv)
buyer.buy(audio)
buyer.buy(computer)
출처 : 따즈아 파이썬 기초부터 실무까지 제대로 배우기
'Python > 객체지향 프로그래밍' 카테고리의 다른 글
(Python) 객체지향 프로그래밍 - 추상 클래스 (0) | 2024.01.24 |
---|---|
(Python) 객체지향 프로그래밍 - 클래스의 다중 상속 (0) | 2024.01.23 |
(Python) 객체지향 프로그래밍 - 클래스 상속 (private) (0) | 2024.01.23 |
(Python) 객체지향 프로그래밍 - 클래스 상속 (1) (0) | 2024.01.16 |
(Python) 파이썬 변수 종류 / None / 오버로딩 & 오버라이딩 (0) | 2024.01.15 |