當方法重載在 Python 中不起作用時?

Patricia Arquette
發布: 2024-10-23 00:01:03
原創
472 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!