>  기사  >  백엔드 개발  >  Python에서 메소드 오버로딩이 작동하지 않는 경우는 언제입니까?

Python에서 메소드 오버로딩이 작동하지 않는 경우는 언제입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-23 00:01:03473검색

When Method Overloading Doesn't Work in Python?

Python의 메서드 오버로딩

Python에서 메서드 오버로딩은 이름은 같지만 매개변수가 다른 여러 메서드를 정의하는 기능입니다. 그러나 이로 인해 예상치 못한 동작이 발생할 수 있습니다.

예 1:

<code class="python">class A:
    def stackoverflow(self):    
        print ('first method')
    def stackoverflow(self, i):
        print ('second method', i)</code>

인수를 사용하여 메서드를 호출하면 두 번째 메서드가 호출됩니다.

<code class="python">ob=A()
ob.stackoverflow(2)
# Output: second method 2</code>

그러나 인수 없이 호출하면 Python에서 오류가 발생합니다.

<code class="python">ob=A()
ob.stackoverflow()
# Output: TypeError: stackoverflow() takes exactly 2 arguments (1 given)</code>

이는 Python이 첫 번째 메서드를 기본 인수가 하나가 아닌 인수가 없는 것으로 간주하기 때문입니다. .

해결책:

이 문제를 해결하려면 기본 매개변수 값을 사용할 수 있습니다.

<code class="python">class A:
    def stackoverflow(self, i='some_default_value'):
        print('only method')</code>

이제 두 호출이 모두 작동합니다.

<code class="python">ob=A()
ob.stackoverflow(2)
# Output: only method
ob.stackoverflow()
# Output: only method</code>

단일 디스패치를 ​​사용한 고급 오버로딩

Python 3.4에서는 다양한 인수 유형에 대해 특정 동작을 정의할 수 있는 단일 디스패치 일반 함수를 도입했습니다.

<code class="python">from functools import singledispatch

@singledispatch
def fun(arg, verbose=False):
    if verbose:
        print(&quot;Let me just say,&quot;, end=&quot; &quot;)
    print(arg)

@fun.register(int)
def _(arg, verbose=False):
    if verbose:
        print(&quot;Strength in numbers, eh?&quot;, end=&quot; &quot;)
    print(arg)

@fun.register(list)
def _(arg, verbose=False):
    if verbose:
        print(&quot;Enumerate this:&quot;)
    for i, elem in enumerate(arg):
        print(i, elem)</code>

이를 통해 다양한 인수 유형으로 fun을 호출하고 적절한 동작을 얻을 수 있습니다.

<code class="python">fun(42)
# Output: Strength in numbers, eh? 42
fun([1, 2, 3])
# Output: Enumerate this:
# 0 1
# 1 2
# 2 3</code>

위 내용은 Python에서 메소드 오버로딩이 작동하지 않는 경우는 언제입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.