90 Python 中特殊方法和運算子過載

2021-10-23 01:22:12 字數 1772 閱讀 8168

目錄

特殊方法和運算子過載

常用的特殊方法

運算子的過載

python的運算子實際上是通過呼叫物件的特殊方法實現的; 比如

方法

說明

例子

__init__

構造方法

物件建立: p = person()

__del__

析構方法

物件**

__repr__, __str__

列印,轉換

print(a)

__call__

函式呼叫

a()__getattr__

點號運算

a.***

__getitem__

索引運算

a[key]

__setitem__

索引賦值

a[key] = value

__len__

長度len(a)

每個運算子實際上都對應了相應的方法, 統計如下:

運算子特殊方法

說明運算子 +

__add__

加法運算子 -

__sub__

減法<, <=, =, ==

__lt__, __le__, __eq__

比較運算子

>, >=, !=

__gt__, __ge__, __ne__

比較運算子

|, ^, &

__or__, __xor__, __and__

或, 異或, 與

<<, >>

__lshift__, __rshift__

左移, 右移

*, /, %, //

__mul__, __truediv__, __mod__, __floordiv__

乘, 浮點除, 模運算(取餘), 整數除

**__pow__

指數運算

我們可以重寫上面的特殊方法, 即實現了運算子的過載;

class person:

def __init__(self,name,age):

self.name = name

self.age = age

def __str__(self):

'''將物件轉化成乙個字串,一般用於print方法'''

return "名字是:,年齡是".format(self.name,self.age)

def __add__(self,other):

if isinstance(other,person):

return self.name + other.name

else:

return "不是同類物件,不能相加"

p1 = person("張三",18)

p2 = person("李四",20)

x = p1 + p2

print(x)

輸出:d:\wwwroot\pyiteam\venv\scripts\python.exe d:/wwwroot/pyiteam/mypro_obj/mypy02.py

張三李四

process finished with exit code 0

python中重寫和特殊構造方法

class bird def init self self.hungry true defeat self if self.hungry print ahaaaaa.self.hungry false else print no,thanks class somebird bird def init...

python中特殊的方法和屬性

class chu object def init self,name,age self.name name self.age age print 楚國 def local self print 楚國在湖北和湖南區域 class chen chu def init self,name,age,wen...

python類中的特殊方法

python類特殊方法 方法功能說明 new 類的靜態方法,用於確定是否建立物件 init 建構函式,生成物件時呼叫 del 析構函式,釋放物件時呼叫 add sub mul truediv floordiv mod pow repr 列印,轉換 setitem 按照索引賦值 getitem 按照索...