[Python]Overloading (오버로딩)
파이썬의 Overloading 에 대해 알아보자.
"""
Python Overloading (파라미터 개수)
"""
# 예1
class SampleA:
def add(self, x, y):
return x + y
def add(self, x, y, z):
return x + y + z
a = SampleA()
# print(f'예1 > {a.add(1, 2)}') : TypeError: add() missing 1 required positional argument: 'z'
print('예1 > ', dir(a))
"""
예1 > ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add']
"""
# 예2 : 동일 이름 메소드 사용예제(자료형에 따른 분기처리)
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('예2 > ', b.add('int', 1, 3))
"""
예2 > 4
"""
# 문자연산
print('예2 > ', b.add('str', 'Hello ', 'jigi!'))
"""
예2 > Hello jigi!
"""
# 예3 : multipledispatch 패키지를 통한 오버로딩
from multipledispatch import dispatch
class SampleC:
@dispatch(int, int)
def product(self, x, y):
return x * y
@dispatch(int, int, int)
def product(self, x, y, z):
return x * y * z
@dispatch(float, float, float)
def product(self, x, y, z):
return x * y * z
c = SampleC()
print('예3 > ', c.product(5, 6))
print('예3 > ', c.product(5, 6, 7))
print('예3 > ', c.product(5.0, 6.0, 7.0))
"""
예3 > 30
예3 > 210
예3 > 210.0
"""
최신 댓글