Programing

파이썬에서 오버로드 된 함수?

crosscheck 2020. 9. 25. 07:27
반응형

파이썬에서 오버로드 된 함수?


파이썬에서 오버로드 된 함수를 가질 수 있습니까? C #에서는 다음과 같이 할 것입니다.

void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}

그런 다음 함수를 호출하면 인수 수에 따라 둘을 구분합니다. 파이썬에서 비슷한 일을 할 수 있습니까?


편집 Python 3.4의 새로운 단일 디스패치 일반 함수에 대해서는 http://www.python.org/dev/peps/pep-0443/을 참조하십시오 .

일반적으로 Python에서 함수를 오버로드 할 필요가 없습니다. Python은 동적 형식 이며 함수에 대한 선택적 인수를 지원합니다.

def myfunction(first, second, third = None):
    if third is None:
        #just use first and second
    else:
        #use all three

myfunction(1, 2) # third will be None, so enter the 'if' clause
myfunction(3, 4, 5) # third isn't None, it's 5, so enter the 'else' clause

정상적인 파이썬에서는 원하는 것을 할 수 없습니다. 두 가지 근사치가 있습니다.

def myfunction(first, second, *args):
    # args is a tuple of extra arguments

def myfunction(first, second, third=None):
    # third is optional

그러나 정말로 이것을하고 싶다면, 확실히 작동하게 만들 수 있습니다 (전통 주의자들을 불쾌하게 할 위험이있는; o). 간단히 말해, wrapper(*args)인수와 대리자의 수를 적절하게 확인 하는 함수를 작성합니다 . 이런 종류의 "해킹"은 보통 데코레이터를 통해 이루어집니다. 이 경우 다음과 같은 결과를 얻을 수 있습니다.

from typing import overload

@overload
def myfunction(first):
    ....

@myfunction.overload
def myfunction(first, second):
    ....

@myfunction.overload
def myfunction(first, second, third):
    ....

당신은 만들어이를 구현 것 overload(first_fn) 기능 (또는 생성자)가 호출 가능한 객체 반환 __call__(*args) 방법 대표단은 위의 설명과 수행 overload(another_fn) 방법 에 위임 할 수있는 추가 기능을 추가합니다.

http://acooke.org/pytyp/pytyp.spec.dispatch.html에서 유사한 예제를 볼 수 있지만 유형별로 메서드가 오버로드됩니다. 매우 유사한 접근 방식입니다 ...

업데이트 : 그리고 비슷한 것 (인수 유형 사용)이 파이썬 3에 추가되었습니다-http: //www.python.org/dev/peps/pep-0443/


예, 가능합니다. Python 3.2.1에서 아래 코드를 작성했습니다.

def overload(*functions):
    return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)

용법:

myfunction=overload(no_arg_func, one_arg_func, two_arg_func)

overload함수에 의해 반환 된 람다 명명되지 않은 인수의 수에 따라 호출 함수를 선택합니다 .

해결책은 완벽하지 않지만 현재로서는 더 나은 것을 쓸 수 없습니다.


직접 불가능합니다. 비록 이것은 일반적으로 눈살을 찌푸 리지만 주어진 인수에 대해 명시 적 유형 검사를 사용할 수 있습니다.

Python is dynamic. If you are unsure what an object can do, just try: and call a method on it, then except: errors.

If you don't need to overload based on types but just on number of arguments, use keyword arguments.


overloading methods is tricky in python. However, there could be usage of passing the dict, list or primitive variables.

I have tried something for my use cases, this could help here to understand people to overload the methods.

Let's take the example use in one of the stackoverflow thread:

a class overload method with call the methods from different class.

def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):

pass the arguments from remote class:

add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}

OR add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}

So, handling is being achieved for list, Dictionary or primitive variables from method overloading.

try it out for your codes

참고URL : https://stackoverflow.com/questions/7113032/overloaded-functions-in-python

반응형