什麼是 Python 中的運算符重載

Python 中的運算符重載意味著提供超出其預定義操作含義的擴展含義。例如,我們使用「+」運算符來相加兩個整數,以及連接兩個字元串或合併兩個列表。我們可以通過「+」運算符被「int」類和「str」類重載來實現這一點。用戶可以注意到,相同的內置運算符或函數對於不同類的對象表現出不同的行為。這個過程被稱為運算符重載。

示例:


print (14 + 32)

# Now, we will concatenate the two strings
print ("Java" + "Tpoint")

# We will check the product of two numbers
print (23 * 14)

# Here, we will try to repeat the String
print ("X Y Z " * 3)

輸出:

46
JavaTpoint
322
X Y Z X Y Z X Y Z

如何在 python 中控制操作符?

假設用戶有兩個對象,它們是用戶定義的數據類型類的物理表示。用戶必須使用「+」操作符相加兩個對象,這會產生一個錯誤。這是因為編譯器不知道如何相加兩個對象。因此,用戶必須定義使用運算符的函數,這個過程被稱為「運算符重載」。用戶可以重載所有現有的操作符,因為他們不能創建任何新的操作符。Python 提供了一些特殊的函數,或者我們可以說是用於執行運算符重載的神奇函數,當它與該運算符相關聯時,就會被自動調用。例如,當用戶使用「+」運算符時,魔法函數 add 將在定義「+」運算符的命令中自動調用。

如何在 Python 中執行二進位「+」運算符:

當用戶在類的用戶定義數據類型上使用運算符時,將自動調用與運算符相關聯的神奇函數。改變操作者行為的過程和定義的函數或方法的行為一樣簡單。

用戶在類中定義方法或函數,操作者根據函數中定義的行為工作。當用戶使用「+」運算符時,會改變一個神奇函數的代碼,用戶就多了一個「+」運算符的含義。

程序 1:簡單地相加兩個對象。

Python 程序,用於簡單地使用重載操作符來相加兩個對象。

示例:


class example:
    def __init__(self, X):
        self.X = X

    # adding two objects
    def __add__(self, U):
        return self.X + U.X
object_1 = example( int( input( print ("Please enter the value: "))))
object_2 = example( int( input( print ("Please enter the value: "))))
print (": ", object_1 + object_2)
object_3 = example(str( input( print ("Please enter the value: "))))
object_4 = example(str( input( print ("Please enter the value: "))))
print (": ", object_3 + object_4) 

輸出:

Please enter the value: 23
Please enter the value: 21
:  44
Please enter the value: Java
Please enter the value: Tpoint
:  JavaTpoint

程序 2:在另一個對象中定義重載操作符

Python 程序,用於定義另一個對象內部的重載操作符。

示例:


class complex_1:
    def __init__(self, X, Y):
        self.X = X
        self.Y = Y

    # Now, we will add the two objects
    def __add__(self, U):
        return self.X + U.X, self.Y + U.Y

Object_1 = complex_1(23, 12)
Object_2 = complex_1(21, 22)
Object_3 = Object_1 + Object_2
print (Object_3)

輸出:

(44, 34)

程序 3:在 Python 中重載比較運算符

用於重載比較運算符的 Python 程序。

示例:


class example_1:
    def __init__(self, X):
        self.X = X
    def __gt__(self, U):
        if(self.X > U.X):
            return True
        else:
            return False
object_1 = example_1(int( input( print ("Please enter the value: "))))
object_2 = example_1(int (input( print("Please enter the value: "))))
if(object_1 > object_2):
    print ("The object_1 is greater than object_2")
else:
    print ("The object_2 is greater than object_1")

輸出:

案例 1:

Please enter the value: 23
Please enter the value: 12
The object_1 is greater than object_2

案例 2:

Please enter the value: 20
Please enter the value: 31
The object_2 is greater than object_1

程序 4:重載等式和小於運算符

用於重載等式和小於運算符的 Python 程序:

示例:


class E_1:
    def __init__(self, X):
        self.X = X
    def __lt__(self, U):
        if(self.X < U.X):
            return "object_1 is less than object_2"
        else:
            return "object_2 is less than object_1"
    def __eq__(self, U):
        if(self.X == U.X):
            return "Both the objects are equal"
        else:
            return "Objects are not equal"

object_1 = E_1(int( input( print ("Please enter the value: "))))
object_2 = E_1(int( input( print ("Please enter the value: "))))
print (": ", object_1 < object_2)

object_3 = E_1(int( input( print ("Please enter the value: "))))
object_4 = E_1(int( input( print ("Please enter the value: "))))
print (": ", object_3 == object_4)

輸出:

案例 1:

Please enter the value: 12
Please enter the value: 23
:  object_1 is less than object_2
Please enter the value: 2
Please enter the value: 2
:  Both the objects are equal

案例 2:

Please enter the value: 26
Please enter the value: 3
: object_2 is less than object_1
Please enter the value: 2
Please enter the value: 5
: Objects are not equal

用於運算符重載的 Python 神奇函數:

二進位運算符:

| 操作員 | 魔法函數 |
| + | 添加 (自身、其他) |
| – |
sub(自身、其他) |
| * |
mul(自身、其他) |
| / |
truediv(自我,其他) |
| // |
floordiv(自身、其他) |
| % |
mod(自身、其他) |
| ** |
pow(自身,其他) |
| >> |
rshift(自身、其他) |
| << | lshift (自我,其他) |
| & |
(自身、其他) |
| | | (自身、其他) |
| ^ |
xor__(自身,其他) |

比較運算符:

| 操作員 | 魔法函數 |
| < | LT(自我,其他) |
| > | GT(自我,其他) |
| <= | LE(自我,其他) |
| >= | 通用電氣 (自身、其他) |
| == |
EQ(自我,其他) |
| != |
NE__(自我,其他) |

分配運算符:

| 操作員 | 魔法函數 |
| -= | ISUB(自我,其他) |
| += | IADD(自我,其他) |
| *= | IMUL(自身、其他) |
| /= | IDIV(自我,其他) |
| //= | IFLOORDIV(自我,其他) |
| %= | IMOD(自我,其他) |
| **= | IPOW(自我,其他) |
| >>= | IRSHIFT(自我,其他) |
| <<= | ILSHIFT(自我,其他) |
| &= | (自身,其他) |
| |= |
IOR(自我,其他) |
| = |
IXOR__(自我,其他) |

一元運算符:

| 操作員 | 魔法函數 |
| – | 否定 (自我,其他) |
| + |
位置 (自身、其他) |
| ~ | _ 反轉 _(自身,其他) |

結論

在本教程中,我們討論了 Python 中的重載運算符以及如何使用它們來執行各種運算符。


原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/247978.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:24
下一篇 2024-12-12 13:24

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論