如何使用自訂方法和屬性擴充內建 Python 類型?

Patricia Arquette
發布: 2024-10-24 17:01:02
原創
375 人瀏覽過

How can I extend built-in Python types with custom methods and attributes?

使用自訂方法和屬性擴充內建Python 類型

在Python 中,您可能會遇到希望內建的場景:具有擴充功能附加方法或屬性的類型。但是,直接更改這些類型是不允許的。

例如,如果您嘗試在 dict 類型中新增 helloWorld() 方法(如 JavaScript 所示),您會發現不支援這種方法。

使用子類化和命名空間替換的解決方法

雖然您無法直接增強原始類型,但存在一個聰明的解決方法。透過對目標類型進行子類化並隨後在內建/全域命名空間中取代它,您可以有效地模仿所需的行為。

這是 Python 中的實作:

<code class="python"># Built-in namespace
import __builtin__

# Extended subclass
class mystr(str):
    def first_last(self):
        if self:
            return self[0] + self[-1]
        else:
            return ''

# Substitute the original str with the subclass on the built-in namespace    
__builtin__.str = mystr

print(str(1234).first_last())  # 14
print(str(0).first_last())  # 00
print(str('').first_last())  # ''

# Note that objects created by literal syntax will not have the extended methods
print('0'.first_last())  # AttributeError: 'str' object has no attribute 'first_last'</code>
登入後複製

在此範例中,mystr 子類別透過新增first_last() 方法來擴充str 型別。 __builtin__.str 賦值將所有內建 str 呼叫重新導向為使用修改後的子類別。因此,使用內建 str() 建構子實例化的物件現在擁有 first_last() 方法。

但是,需要注意的是,使用文字語法(「string」)建立的物件仍將保留為未修改的 str 類型,不會繼承自訂方法。

以上是如何使用自訂方法和屬性擴充內建 Python 類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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