Python中,類的特殊方法與內置函數的關聯

来源:https://www.cnblogs.com/shuezhang/archive/2023/04/06/17293627.html
-Advertisement-
Play Games

教程簡介 什麼是SEO和SEO文案 - 一個關於搜索引擎優化(SEO)入門教程,以瞭解什麼是SEO和各種SEO工具和技術,包括白帽黑帽Spamdexing和Meta標簽關鍵詞主題標題超鏈接圖像網頁優化和搜索引擎抓取索引處理相關性計算結果檢索隱藏元標記填充門口網關頁面劫持 搜索引擎優化,又稱為SEO, ...


目錄

Python類

Python類的設計原則

  • 封裝(Encapsulation):Python類被設計用來將相關數據和行為封裝到一個獨立的單元中。
  • 繼承(Inheritance):Python支持繼承,允許子類從父類繼承屬性和方法。有利於代碼的復用和創建相關類的層次結構。
  • 多態(Polymorphism):Python支持多態,也就意味著不同類的對象可以被視為同一類型,這使得代碼的設計具有更大的靈活性。
  • 組合(Composition):Python鼓勵使用組合而不是繼承,這意味著對象是由其他對象組成的,而不是由父類派生的。這可以使您的代碼更加模塊化,更易於維護。
  • Duck類型(Duck typing):Python使用Duck類型,這意味著對象的類型由其行為而非類決定,這樣更容易編寫可用於各種對象的通用代碼。
  • 特殊方法(Special methods):Python提供了許多特殊方法,允許為內置操作自定義行為。例如__len__方法允許你定義len()函數如何處理類的對象。
  • 可讀性(Readability):與Python的一般設計原則一樣,類也應該優先考慮可讀性和簡單性,也就是說,對方法和屬性使用清晰簡潔的名稱,避免不必要的複雜性。
特殊方法【Special methods】

Python中的特殊方法是一系列預定義的方法,允許你為對象上的內置操作定義自定義行為,使用雙下劃線首碼和尾碼來識別,也成為"dunder"方法。這裡講述一些Python類中常用的特殊方法:

  1. __init__(self, ...): 這是構造方法,對象創建時調用,用於初始化對象的屬性並設置其初始狀態。
  2. __str__(self): 返回對象的字元串表示,用於創建一個人類可讀的字元串表示。
  3. __repr__(self): 返回對象的字元串表示,用於創建可用於創建對象的字元串表示。
  4. __len__(self): 返回對象的長度,供len()函數使用。
  5. __getitem__(self, key): 這個方法允許你以括弧的形式訪問對象的元素,可以使用[]來訪問元素。
  6. __setitem__(self, key, value): 這個方法允許你以括弧的形式設置對象元素的值,可以使用[]來修改元素的值。
  7. __delitem__(self, key): 這個方法允許你以括弧的形式刪除對象的元素。
  8. __add__(self, other): 自定義對象的+操作方式。
  9. __eq__(self, other): 自定義對象的==操作方式。
  10. __lt__(self, other): 自定義對象的<操作方式。

這隻是較為常用的一些,Python中還提供了很多其他的特殊方法。在你的自定義類中,通過定義這些方法,你可以自定義你對象的行為以更直觀、更方便地使用它們。

示例一:

class Person:
    def __init__(self, name, age, items):
        self.name = name
        self.age = age
        self.items = items
    
    def __str__(self):
        return f"{self.name} ({self.age})"
    
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
    
    
person = Person("Alice", 25)
print(person)       # output: Alice (25)
print(repr(person)) # output: Person(name='Alice', age=25)

示例二:

class MyObject:
    def __init__(self, items):
        self.items = items
    
    def __len__(self):
        return len(self.items)
    
    def __getitem__(self, index):
        return self.items[index]
    
    def __setitem__(self, index, value):
        self.items[index] = value
    
    def __delitem__(self, index):
        del self.items[index]
    
    def __add__(self, other):
        new_items = self.items + other.items
        return MyObject(new_items)
    
    def __eq__(self, other):
        if isinstance(other, MyObject):
            return self.items == other.items
        return False
    
    def __lt__(self, other):
        if isinstance(other, MyObject):
            return len(self.items) < len(other.items)
        return NotImplemented
    
obj = MyObject([1, 2, 3])
print(len(obj))  # output: 3
print(obj[1])    # output: 2
obj[1] = 4
print(obj.items) # output: [1, 4, 3]
del obj[1]
print(obj.items) # output: [1, 3]
obj1 = MyObject([1, 2])
obj2 = MyObject([3, 4])
obj3 = obj1 + obj2
print(obj3.items) # output: [1, 2, 3, 4]

obj4 = MyObject([1, 2, 3])
obj5 = MyObject([4, 5])
obj6 = MyObject([1, 2, 3])

print(obj1 == obj2) # output: False
print(obj1 == obj3) # output: True

print(obj1 < obj2) # output: False
print(obj2 < obj1) # output: True
  • 格式化字元串

詳細解釋下這句話,字元串文字前面的f用於創建格式化字元串(f-string, formatted string),格式化字元串是一種允許你使用大括弧{}將表達式嵌入占位符中的字元串,這些表達式將在運行時被求值並替換為它們的值。

例如下麵的代碼中,嵌入的表達式有兩個{self.name}{self.age},運行時,會將這兩個表達式替換為其值並返回。

f"Person(name='{self.name}', age={self.age})"
Duck typing

The term "duck typing" comes from the saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

Duck類型是Python等動態類型編程語言中使用的一種編程概念。在Duck類型中,一個對象的類型是由它的行為決定的,而不是它的class或者type決定的。Duck Typing一詞來源於這樣一句話“如果它看起來像鴨子,游泳像鴨子,嘎嘎叫像鴨子,那麼它可能就是鴨子”。

Duck類型使得程式員可以編寫適用於任何具有必要屬性和方法的對象的代碼,比如:

def print_size(obj):
    print(len(obj))

該函數接收一個參數obj並列印其size。由於Python使用duck類型,這個函數適用於任何包含len()方法的對象,比如字元串、列表、元組、字典等等(string, list, tuple, dictionaries and so on)。

使用Duck類型可以編寫更加通用的代碼,使得代碼更加容易復用和維護。

但是使用Duck類型也極易出錯,為了避免這些錯誤,可是使用類型檢查來確保你的代碼運行在你期望的對象類型上。

內置函數
  • 關於len(obj)中的len()

len()是Python內置函數,用於返回對象的長度。

len()可被用於多種類型的對象,包括字元串、列表、元組、字典、集合等,並返回對象中元素的數目。

在自定義的類中,通過實現特殊方法__len__()來使用len()函數來檢索對象的長度,返回值要求是整數。

  • 關於內置函數的更多細節

    上面講述的是其中一個內置函數,詳細看下,Python中的一些其他內置函數:

    1. print(): 列印特定信息到控制台,對應__str__()
    2. type(): 返回對象類型,對應__class__()
    3. len(): 返回對象長度,對應__len__()
    4. range(): 生成數字序列,預設從0開始,步長為1,直到某個終止值[不包括]
    5. input(): 接收控制台輸入
    6. int(), float(), str(): 將輸入轉換為某種特定類型,整數、浮點數或字元串。
    7. max(), min(): 在一個序列中找到最大值和最小值,適用於列表、元組、集合等,對應__gt____lt__()
    8. sum(): 取得序列值得和,適用於列表、元組、集合等
    9. sorted()以升序排序一個序列,適用於列表、元組、集合等
    10. zip(): 將兩個或多個序列合併為一個元組序列

示例一:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person(name='{self.name}', age={self.age})"

    def __lt__(self, other):
        return self.age < other.age

    def __gt__(self, other):
        return self.age > other.age

p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p3 = Person("Charlie", 20)

people = [p1, p2, p3]

print(p1)        # Output: Person(name='Alice', age=25)
print(min(people).name)  # Output: 'Charlie'
print(max(people).name)  # Output: 'Bob'

特殊方法與內置函數的對應:

特殊方法 內置函數 備註
__len__() len() 返回對象的長度
__getitem__(), __setitem__() [] 定義對象元素的訪問和修改行為
__iter__(), __next__() for 定義對象的迭代行為
__contains__() in 判斷對象是否包含某個特定元素
__add__(), __radd__() + 定義對象的加法行為
__sub__(), __rsub__() - 定義對象的減法行為
__mul__(), __rmul__() * 定義對象的乘法行為
__divmod__(), __rdivmod__() divmod() 定義對象的餘數除法行為
__eq__(), __ne__() ==, != 定義對象的判等操作
__lt__(), __le__(),
__gt__(), __ge__()
<, <=, >, >= 定義對象間的比較操作
__hash__() hash() 定義對象的哈希值(hash value)

English Version

The key design principles for Python classes

  • Encapsulation:Python classes are designed to encapsulated related data and bahavior into a single unit.
  • Inheritance:Python supports inheritance, which allows classes to inherit attributes and methods from parent classes. This makes it easier to reuse code and create hierarchies of related classes.
  • Polymorphism:Python supports polymorphism, which means that objects of different classes can be treated as if they are the same type. This allows for greater flexibility in the design of your code.
  • Composition:Python encourages the use of composition over inheritance, which means that objects are made up of other objects rather than being derived from parent classes. This can make your code more modular and easier to maintain.
  • Duck typing: Python uses duck typing, which means that the type of an object is determined by its behavior rather than its class. This makes it easier to write generic code that works with a variety of objects.
  • Special methods: Python has a number of special methods that allow you to define custom behavior for built-in operations. For example, the __len__ method allows you to define how the len() function works with objects of your class.
  • Readability: As with the general design principles of Python, classes should also prioritize readability and simplicity. This means using clear and concise names for methods and attributes, avoiding unnecessary complexity, and following PEP 8 guidelines for formatting.
Special methods

Special methods in Python are a set of predefined methods that allow you to define custom behavior for built-in operations on your objects. They are identified by their double underscore prefix and suffix, also known as "dunder" methods.

Here are some of the most commonly used special methods in Python:

  1. __init__(self, ...): This is the constructor method that is called when an object is called. It initializes the object's attributes and sets its initial state.
  2. __str__(self): This methods returns a string representation of the object. It's called by the str() function and by the print() statement.
  3. __repr__(self): This method returns a string representation of the object that can be used to recreate the object. It is called by the repr() function and by the interactive Python shell. The difference between __str__ and __repr__ is that __repr__ is used to create an unambiguous string representation of an object that can be used to recreate the object, while __str__ is used to create a human-readable string representation of an object.
  4. __len__(self): This method returns the length of the object. It is called by the len() function.
  5. __getitem__(self, key): This method allows you to access an item in the object using bracket notation. It is called when you use the bracket operation([]) on the object.
  6. __setitem__(self, key, value): This method allows you to set the value of an item in the object using bracket notation. It is called when you use the bracket operation([]) on the object with an assignment.
  7. __delitem__(self, key): This method allows you to delete an item from the object using bracket notation. It is called when you use the del statement on the object with bracket notation.
  8. __add__(self, other): This method allows you to define how the + operator works with your object. It is called when you use the + operator on the object.
  9. __eq__(self, other): This method allows you to define how the == operator works with your object. It is called when you use the == operator on the object.
  10. __lt__(self, other): This method allows you to define how the < operator works with your object. It is called when you use the < operator on the object.

There are many other special methods available in Python, but these are some of the most commonly used ones. By defining these methods in your classes, you can customize the behavior of your objects and make them more intuitive and convenient to use.

Example1:

class Person:
    def __init__(self, name, age, items):
        self.name = name
        self.age = age
        self.items = items
    
    def __str__(self):
        return f"{self.name} ({self.age})"
    
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
    
    
person = Person("Alice", 25)
print(person)       # output: Alice (25)
print(repr(person)) # output: Person(name='Alice', age=25)

Example2:

class MyObject:
    def __init__(self, items):
        self.items = items
    
    def __len__(self):
        return len(self.items)
    
    def __getitem__(self, index):
        return self.items[index]
    
    def __setitem__(self, index, value):
        self.items[index] = value
    
    def __delitem__(self, index):
        del self.items[index]
    
    def __add__(self, other):
        new_items = self.items + other.items
        return MyObject(new_items)
    
    def __eq__(self, other):
        if isinstance(other, MyObject):
            return self.items == other.items
        return False
    
    def __lt__(self, other):
        if isinstance(other, MyObject):
            return len(self.items) < len(other.items)
        return NotImplemented
    
obj = MyObject([1, 2, 3])
print(len(obj))  # output: 3
print(obj[1])    # output: 2
obj[1] = 4
print(obj.items) # output: [1, 4, 3]
del obj[1]
print(obj.items) # output: [1, 3]
obj1 = MyObject([1, 2])
obj2 = MyObject([3, 4])
obj3 = obj1 + obj2
print(obj3.items) # output: [1, 2, 3, 4]

obj4 = MyObject([1, 2, 3])
obj5 = MyObject([4, 5])
obj6 = MyObject([1, 2, 3])

print(obj1 == obj2) # output: False
print(obj1 == obj3) # output: True

print(obj1 < obj2) # output: False
print(obj2 < obj1) # output: True
built-in functions
  • what's len() in len(obj) ?

In the context of len(obj), len() is a built-in Python function that returns the length of an object.

The len() function can be applied to different types of objects in Python, such as strings, lists, tuples, dictionaries, and sets, and it returns the number of elements in the object.

For example, len("Hello") returns 5 because there are 5 characters in the string "Hello", and len([1, 2, 3]) returns 3 because there are 3 elements in the list [1, 2, 3].

In custom classes, the len() function can be used to retrieve the length of objects by implementing the __len__() special method, which should return an integer representing the length of the object.

  • more details about built-in Python functions
  1. print(): This function is used to print the specified message or object to the console. It can take multiple arguments, separated by commas, and can also use formatting to display variables and values.
  2. type(): This function returns the type of an object. It takes one argument and returns the type of that object.
  3. len(): This function returns the length of an object. It can be used with objects such as strings, lists, tuples, dictionaries, and sets.
  4. range(): This function generates a sequence of numbers, starting from a specified start value (by default 0), and incrementing by a specified step value (by default 1), up to but not including a specified stop value.
  5. input(): This function is used to get input from the user via the console. It takes one optional argument, which is the prompt to display to the user, and returns a string containing the user's input.
  6. int(), float(), str(): These functions are used to convert values from one type to another. int() converts a value to an integer, float() converts a value to a floating-point number, and str() converts a value to a string.
  7. max(), min(): These functions are used to find the maximum or minimum value in a sequence. They can be used with objects such as lists, tuples, and sets.
  8. sum(): This function is used to find the sum of all the values in a sequence. It can be used with objects such as lists, tuples, and sets.
  9. sorted(): This function is used to sort a sequence in ascending order. It can be used with objects such as lists, tuples, and sets.
  10. zip(): This function is used to combine two or more sequences into a single sequence of tuples. It takes two or more arguments and returns a zip object containing tuples of elements from the input sequences.

These are just a few examples of the built-in Python functions. Python has many more built-in functions that can be used to perform a variety of tasks, such as manipulating strings, performing mathematical calculations, working with files and directories, and more.




關註我的公眾號 不定期推送資訊,接受私信許願

作者:iSherryZhang 出處:https://www.cnblogs.com/shuezhang/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 至此,C++/Qt網路通訊模塊設計與實現已分析完畢,代碼已應用於實際產品中。 C++/Qt網路通訊模塊設計與實現(一) 該章節從模塊的功能需求以及非功能需求進行分析,即網路通訊模塊負責網路數據包的發送、接收以及對外提供功能調用以及介面回調,其不進行產品業務的實現,達到平臺化復用的目的,給出了類圖,如 ...
  • SpringCloud Eureka-服務註冊與發現01 1.Eureka介紹 1.1學習Eureka前的說明 目前主流的服務註冊&發現的組件是 Nacos,但是 Eureka 作為老牌經典的服務註冊&發現技術還是有必要學習一下,原因: (1)一些早期的分散式微服務項目使用的是 Eureka,在工作 ...
  • 靜態代理可以在不改變原有代碼的情況下,增加新的功能和操作,對原有對象進行擴展。 靜態代理要求真實對象和代理對象都實現同一個介面,由代理對象代理真實角色的介面實現,併在實現前後增加新的操作。 public class StaticProxy{ public static void main(Strin ...
  • static關鍵字,main()方法,代碼塊,final關鍵字 static關鍵字的使用: static:靜態的 static可以修飾:屬性、方法、代碼塊、內部類 使用static修飾的變數:靜態變數(類變數) 3.1屬性: *實例變數:*我們創建了多個類的對象,每個對象都擁有一套獨立的類的非靜態屬 ...
  • 最近接觸到用java代碼調用主機的命令部分感覺有點意思整理總結一下 環境jdk1.8 操作系統win10,不用引入其他的包jdk自帶的api就可以 一、java調用ping命令 import java.io.BufferedReader; import java.io.InputStreamRead ...
  • 項目中常有需求要求不能明文傳送某些關鍵字元,也許會被某些網關被攔截掉,那應該怎麼解決這個問題呢? 字元串轉 base64後的加密與解密 import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; private static Strin ...
  • Java原生支持多線程,主要通過以下四種方式實現多線程: 繼承Thread類 實現Runnable介面 實現Callable介面 線程池 繼承Thread類 通過創建Thread類的子類,並重寫run()方法,通過調用start()方法啟動線程。 public class TestThread ex ...
  • 前言 一、人物簡介 第一位閃亮登場,有請今後會一直教我們C語言的老師 —— 自在。 第二位上場的是和我們一起學習的小白程式猿 —— 逍遙。 二、構成和表示方式 邏輯運算符是用來比較和操作布爾值的運算符 C語言中的邏輯運算符主要有3個,如下表所示 | 運算符 | 名稱 | 示例 | 描述 | | : ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...