python深入講解魔術(shù)方法
什么是魔術(shù)方法(魔法方法/特殊方法)
- 魔術(shù)方法都不需要手動去調(diào)用
- 是在特定的情況下觸發(fā)的
- 魔術(shù)方法都是在python事先定義好的,在定義方法的時候,不要使用魔術(shù)方法的命名規(guī)范
- 魔術(shù)方法是雙劃線開頭,雙劃線結(jié)尾的
一、python內(nèi)置的基本魔術(shù)方法
init方法
init 是類在實例化時的方法
# 例如 class Mytest(): def __init__(self): print("----這是魔術(shù)方法__init__") Mytest()
call方法
__call__方法的作用 :實現(xiàn)對象可調(diào)用
1.沒有實現(xiàn) __call__方法時,對象是不可以被調(diào)用的
# 類 class Demo: pass # 判斷對象是否可被調(diào)用,有個函數(shù)可以使用——callable print(callable(Demo)) ======》 返回True,可被調(diào)用 # demo類創(chuàng)建出來的對象是否可被調(diào)用,是不能的被調(diào)用的 obj = Demo() obj()
執(zhí)行結(jié)果:提示:‘Demo’ object is not callable ----- 沒有__call__方法
2.如果要類創(chuàng)建對象出來的對象可別調(diào)用,就要用到__call__方法
class Demo: def __call__(self, *args,**kwds): print("這是__call__方法執(zhí)行了") print(callable(Demo)) # demo類創(chuàng)建出來的對象是否可被調(diào)用(不能被調(diào)用) obj = Demo() obj() # 等同于:obj.__call__() 方法 obj() obj()
new 方法
__new__方法的作用 : 是創(chuàng)建對象的方法
__init__方法的作用 : 是用來初始化對象的方法
類的對象要能被調(diào)用:
首要new方法創(chuàng)建對象,然后通過init方法初始化
什么時候會需要用到New方法:
干預類實例化對象的過程
注意點:
- 一般情況不要重寫new方法,除非有特定的需求需要使用new方法來實現(xiàn)
- 定義了new方法之后,需要調(diào)用父類的new來創(chuàng)建對象 并返回
class MyTest(object): # 初始化對象 def __init__(self): print('-------init------方法') # 創(chuàng)建對象 def __new__(cls, *args, **kwargs): print('------new方法-------') obj = super().__new__(cls) # 調(diào)用父類的new來創(chuàng)建對象 return obj # 并返回新的對象 obj = MyTest()
bool(self)方法
定義當被 bool() 調(diào)用時的行為,應(yīng)該返回 True 或 False
class Demo: def __bool__(self): """內(nèi)置函數(shù)bool(),獲取對象的布爾值是會執(zhí)行這個方法""" return True b = Demo() # 獲取對象的布爾值,返回True 或 False print(bool(b)) =====》 返回 True
str(self)方法
使用print去輸出對象時,輸出到控制臺的內(nèi)容是由__str__來決定的
class Demo: def __str__(self): """ 使用print去輸出對象時,輸出到控制臺的內(nèi)容是由__str__來決定的 """ return 'zifuc' b = Demo() # str方法 s = str('123') print(s) =======》 返回 123
repr(self)方法
這個方法也是控制對象顯示的,一般會顯示對象的原始信息
class Demo: def __repr__(self): """ 這個方法也是控制對象顯示的,一般會顯示對象的原始信息 """ return 'repr-number' b = Demo() # repr方法 s = repr('123') print(s) =======》 返回 '123'
len(self)方法
獲取對象的長度
class Demo: def __len__(self): """ 這個方法是獲取對象的長度 :return: """ return 3 b = Demo() # 獲取對象的長度 print(len(b)) =====》 返回 3
hash(self)方法
返回對象的hash值
class Demo: def __hash__(self): """ 這個方法是獲取hash值 :return: """ return 999 b = Demo() # 獲取hash值 print(hash(b)) =====》 返回 999
二、python中容器類型的的魔術(shù)方法
setitem(self, key, value)方法
定義設(shè)置容器中指定元素的行為,語法:self[key] = value
class Mytest: def __setitem__(self, key, value): return setattr(self, key, value) m = Mytest() print(m.__dict__) 沒有數(shù)據(jù),為空字典 m.name = 'gddg' ==== 》 設(shè)置name屬性,值為gddg m['age'] = 18 ==== 》 設(shè)置age屬性,值為18
getitem(self, item)方法
定義獲取容器中指定元素的行為,語法: self[key]
class Mytest: def __getitem__(self,item): return getattr(self,item) m = Mytest() print(m['name']) ==== 》 name屬性,值為gddg
delitem(self, item)方法
定義刪除容器中指定元素的行為,相當于 del self[key]
class Mytest: def __delitem__(self,item): delattr(self,item) m = Mytest() del m['name'] ==== 》 刪除name屬性
contains(self, item)方法
定義當使用成員測試運算符(in 或 not in)時的行為, 返回 True 或 False
class MyTest: def __contains__(self, item): """成員運算符觸發(fā)的魔術(shù)方法""" return True a = MyTest() b = MyTest() print(a in b) =======》 返回 True
迭代協(xié)議:__iter__方法
定義當?shù)萜髦械脑氐男袨?/p>
class IterClass: def __iter__(self): """ __iter__方法的返回值必須是一個迭代器 """ return iter([11, 22, 33, 44]) ===== 》返回一個迭代器 li = IterClass() for i in li : print(i ) for遍歷對象: 1、執(zhí)行對象的__iter__方法(返回迭代器) 2、在循環(huán)使用next對迭代器進行迭代
三、python中算數(shù)運算符的魔術(shù)方法
add(a,b)方法 和 sub(a,b)方法
a = 1 b = 2 print(a + b) ======》 實際執(zhí)行的是:a.__add__(a,b) print(a - b) ======》 實際執(zhí)行的是:a.__sub__(a,b)
字符串類型的是否支持加減的操作
a = '123' b = '12' print(a + b) ======》 實際執(zhí)行的是:a.__add__(a,b) print(a - b) ======》 實際執(zhí)行的是:a.__sub__(a,b)
對字符串對象沒有實現(xiàn)__sub__方法,所以不支持對象直接使用 -
自己在重新定義__sub__方法,實現(xiàn)對字符串對象的減法
class MyStr(str): def __sub__(self, other): return self.replace(other, '') a = MyStr('1234') b = MyStr('123') print(a + b) ======= 》 返回 1234123 print(a - b) ======= 》 返回 4
到此這篇關(guān)于python深入講解魔術(shù)方法的文章就介紹到這了,更多相關(guān)python魔術(shù)方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python基礎(chǔ)之函數(shù)的定義和調(diào)用
這篇文章主要介紹了python函數(shù)的定義和調(diào)用,實例分析了Python中返回一個返回值與多個返回值的方法,需要的朋友可以參考下2021-10-10Python爬蟲自動化獲取華圖和粉筆網(wǎng)站的錯題(推薦)
這篇文章主要介紹了Python爬蟲自動化獲取華圖和粉筆網(wǎng)站的錯題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01python?matplotlib實現(xiàn)條形圖的填充效果
這篇文章主要為大家詳細介紹了python?matplotlib實現(xiàn)條形圖的填充效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04tensorflow實現(xiàn)打印ckpt模型保存下的變量名稱及變量值
今天小編就為大家分享一篇tensorflow實現(xiàn)打印ckpt模型保存下的變量名稱及變量值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01使用python 計算百分位數(shù)實現(xiàn)數(shù)據(jù)分箱代碼
這篇文章主要介紹了使用python 計算百分位數(shù)實現(xiàn)數(shù)據(jù)分箱代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例
下面小編就為大家分享一篇用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12