logo

파이썬 | 메소드 오버로딩

메소드 오버로딩:

자바 배열 반환

두 개 이상의 메서드가 이름은 동일하지만 매개변수 개수나 매개변수 유형이 다르거나 둘 다 다릅니다. 이러한 메소드를 오버로드된 메소드라고 하며 이를 메소드라고 합니다. 과부하 .



다른 언어와 마찬가지로(예: C++의 메소드 오버로딩 ) 그렇습니다. Python은 기본적으로 메서드 오버로딩을 지원하지 않습니다. 그러나 Python에서 메서드 오버로딩을 달성하는 방법에는 여러 가지가 있습니다.

Python에서 메서드 오버로드의 문제점은 메서드를 오버로드할 수 있지만 최근에 정의된 메서드만 사용할 수 있다는 것입니다.

파이썬3








# First product method.> # Takes two argument and print their> # product> def> product(a, b):> >p>=> a>*> b> >print>(p)> # Second product method> # Takes three argument and print their> # product> def> product(a, b, c):> >p>=> a>*> b>*>c> >print>(p)> # Uncommenting the below line shows an error> # product(4, 5)> # This line will call the second product method> product(>4>,>5>,>5>)>

>

>

산출

100>

위 코드에서는 Python이 메서드 오버로딩을 지원하지 않기 때문에 두 번째 제품 메서드만 사용할 수 있는 두 가지 제품 메서드를 정의했습니다. 동일한 이름과 다른 인수를 가진 여러 메서드를 정의할 수 있지만 가장 최근에 정의된 메서드만 사용할 수 있습니다. 다른 메서드를 호출하면 오류가 발생합니다. 여기서 전화하는 것처럼 제품(4,5) 최근에 정의된 제품 메소드가 세 개의 인수를 사용하므로 오류가 발생합니다.

따라서 위의 문제를 극복하기 위해 메소드 오버로딩을 달성하는 다양한 방법을 사용할 수 있습니다.

방법 1(가장 효율적인 방법은 아님):

인수를 사용하여 동일한 함수가 인수에 따라 다르게 작동하도록 할 수 있습니다.

파이썬3




# Function to take multiple arguments> def> add(datatype,>*>args):> ># if datatype is int> ># initialize answer as 0> >if> datatype>=>=> 'int'>:> >answer>=> 0> ># if datatype is str> ># initialize answer as ''> >if> datatype>=>=> 'str'>:> >answer>=> ''> ># Traverse through the arguments> >for> x>in> args:> ># This will do addition if the> ># arguments are int. Or concatenation> ># if the arguments are str> >answer>=> answer>+> x> >print>(answer)> # Integer> add(>'int'>,>5>,>6>)> # String> add(>'str'>,>'Hi '>,>'Geeks'>)>

>

>

산출

11 Hi Geeks>

방법 2(효율적이지 않음):

Python에서 사용자 정의 함수를 사용하여 메소드 오버로딩을 달성할 수 있습니다. 없음 키워드를 기본 매개변수로 사용합니다.

코드 설명:

add 메소드의 첫 번째 매개변수는 None으로 설정됩니다. 그러면 매개변수를 사용하거나 사용하지 않고 호출할 수 있는 옵션이 제공됩니다.

add 메소드에 인수를 전달할 때(작업 중):

  • 이 메서드는 두 매개변수가 모두 사용 가능한지 여부를 확인합니다.
  • 이미 기본 매개변수 값을 None으로 지정했으므로 값 중 하나라도 전달되지 않으면 None으로 유지됩니다.
  • If-Else 문을 사용하면 각 매개변수를 단일 문으로 확인하여 메서드 오버로드를 달성할 수 있습니다.

파이썬3




# code> def> add(a>=>None>, b>=>None>):> ># Checks if both parameters are available> ># if statement will be executed if only one parameter is available> >if> a !>=> None> and> b>=>=> None>:> >print>(a)> ># else will be executed if both are available and returns addition of two> >else>:> >print>(a>+>b)> # two arguments are passed, returns addition of two> add(>2>,>3>)> # only one argument is passed, returns a> add(>2>)>

>

>

산출

5 2>

위 메서드의 문제점은 다중 if/else 문을 사용하여 코드를 더 복잡하게 만들고 메서드 오버로드를 달성하는 데 바람직한 방법이 아니라는 것입니다.

방법 3(효율적인 방법):

다중 디스패치 데코레이터를 사용하여

다중 디스패치 데코레이터는 다음 방법으로 설치할 수 있습니다:

pip3 install multipledispatch>

장치에 pip가 설치되어 있지 않은 경우:

Windows의 경우 여기를 클릭하세요.

Linux의 경우 여기를 클릭하세요.

.tostring 자바

파이썬3




from> multipledispatch>import> dispatch> # passing one parameter> @dispatch>(>int>,>int>)> def> product(first, second):> >result>=> first>*>second> >print>(result)> # passing two parameters> @dispatch>(>int>,>int>,>int>)> def> product(first, second, third):> >result>=> first>*> second>*> third> >print>(result)> # you can also pass data type of any value as per requirement> @dispatch>(>float>,>float>,>float>)> def> product(first, second, third):> >result>=> first>*> second>*> third> >print>(result)> # calling product method with 2 arguments> product(>2>,>3>)># this will give output of 6> # calling product method with 3 arguments but all int> product(>2>,>3>,>2>)># this will give output of 12> # calling product method with 3 arguments but all float> product(>2.2>,>3.4>,>2.3>)># this will give output of 17.985999999999997>

>

>

산출:

6 12 17.985999999999997>

백엔드에서 Dispatcher는 다양한 구현을 저장하는 개체를 생성하고 런타임에 전달된 매개 변수의 유형 및 수에 따라 적절한 메서드를 선택합니다.