__call__(파이썬)
Python에는 일련의 내장 메소드가 있으며 __call__> 그 중 하나입니다. 그만큼 __call__> 메서드를 사용하면 Python 프로그래머는 인스턴스가 함수처럼 동작하고 함수처럼 호출될 수 있는 클래스를 작성할 수 있습니다. 인스턴스가 함수로 호출되는 경우; 이 메소드가 정의된 경우 x(arg1, arg2, ...)> 은 약칭이다 x.__call__(arg1, arg2, ...)> .
object() is shorthand for object.__call__()
예시 1:
class> Example:> > def> __init__(> self> ):> > print> (> 'Instance Created'> )> > > # Defining __call__ method> > def> __call__(> self> ):> > print> (> 'Instance is called via special method'> )> > # Instance created> e> => Example()> > # __call__ method will be called> e()> |
출력 :
Instance Created Instance is called via special method
예시 2:
class> Product:> > def> __init__(> self> ):> > print> (> 'Instance Created'> )> > > # Defining __call__ method> > def> __call__(> self> , a, b):> > print> (a> *> b)> > # Instance created> ans> => Product()> > # __call__ method will be called> ans(> 10> ,> 20> )> |
출력 :
Instance Created 200