문제점 Java 같으면 class 내에서 메소드 오버로딩을 지원한다. 똑같은 이름을 한 뒤에 argument 값 갯수가 달라도 입력 받은 값에 맞추어서 실행된다. 그러나 파이썬에서는 이러면 에러가 뜬다!!(?)
# Ex1
# 동일 이름 메소드 사용 예제
# 동적 타입 검사 -> 런타임에 실행(타입 에러가 실행시에 발견)
class SampleA():
def add(self, x, y):
return x + y
def add(self, x, y, z):
return x + y + z
# 패킹으로 해결 가능하지만..
# def add(self, *args):
# return sum(args)
a = SampleA()
print(dir(a))
위에 같으면 에러가 뜬다..
# Ex2
# 동일 이름 메소드 사용 예제
# 자료형에 따른 분기 처리
class SampleB():
def add(self, datatype, *args):
if datatype == 'int':
return sum(args)
if datatype == 'str':
return ' '.join([x for x in args])
b = SampleB()
print(dir(b))
print(b.add('int', 5, 6))
print(b.add('str', 'Hi', 'Python'))
조건을 주어서 상태를 확인한 뒤에 만드는 방법이다 그러나 새로운 방법이 나왔다.
우선은 multipledispatch 를 다운로드 해야한다.
# Ex3
# multipledispatch 패키지를 통한 오버로딩
from multipledispatch import dispatch
class SampleC():
@dispatch(int, int)
def product(x, y):
return x + y
@dispatch(int, int, int)
def product(x, y, z):
return x * y * z
@dispatch(float, float, float)
def product(x, y, z):
return x * y * z
c = SampleC()
print(c.product(5, 6))
print(c.product(5, 6, 7))
print(c.product(5.0, 6.0, 7.1))