반응형
Python의 Variable Arguments와 Ellipsis를 정리한다.
Python Variable Arguments 어디에 적용하고 싶은가?
다른 사람의 class를 기반으로 상속받아 코딩하려고 한다. 내가 만드는 child class에서, parent class의 생성자를 그대로 호출하고 싶다. 이때 같은 내용이 반복되지 않도록 Variable Arguments(가변인자)를 쓰려고 한다.
class parent():
def __init__(self, param1: int, param2:np.ndarray, ... ):
self.param1 = param1
...
class OurWrapper(parent):
def __init__(*args, **kwargs):
super().__init__(*args, **kwargs)
def main():
return
args에는 array로 parameter 값이 들어가고, kwargs에는 key=value로 dictionary 값이 들어간다.
Ellipsis(엘리프시스)
python에서 ... object가 나온적이 있다. 크게 가지 방식으로 쓰인다.
- numpy의 indexing
3차원 이상의 array를 indexing할때 남은ndarray_3d[1,...]
로 하면, 3차원 arrray의 첫번째 2D table을 가져올 수 있다. - TBD(To Be Determined) not implemented, pass
아직 구현이 안 됐을 때, - Type hint
- variable-length tuple of homogeneous
아래 예시와 같이 - typelist of arguments to a callable
variable: tuple[float,...] # 변수에 type hint
# python3.9부터 내장된 type hint 를 쓸 수 있다. 이전에는 typing library를 사용했다,
def(arg: int | str)->int: # typing에선 Union과 Any를 이용했다.
return
from typing import Callable
# int를 return하는 함수만 parameter로 받겠다.
def calculate(i: int, action: Callable[..., int], *args: int) -> int:
return action(i, *args)
# int,int -> int prototype 함수만 받겠다.
def apply_function(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
# callable object에선 return 값은 필수로 넣어야 한다. 아무것이나 반환하고 싶은 경우 typing의 any를 쓰자.
Ref.
반응형