python深入講解魔術方法
什么是魔術方法(魔法方法/特殊方法)
- 魔術方法都不需要手動去調用
- 是在特定的情況下觸發(fā)的
- 魔術方法都是在python事先定義好的,在定義方法的時候,不要使用魔術方法的命名規(guī)范
- 魔術方法是雙劃線開頭,雙劃線結尾的
一、python內置的基本魔術方法
init方法
init 是類在實例化時的方法
# 例如
class Mytest():
def __init__(self):
print("----這是魔術方法__init__")
Mytest()
call方法
__call__方法的作用 :實現對象可調用
1.沒有實現 __call__方法時,對象是不可以被調用的
# 類
class Demo:
pass
# 判斷對象是否可被調用,有個函數可以使用——callable
print(callable(Demo)) ======》 返回True,可被調用
# demo類創(chuàng)建出來的對象是否可被調用,是不能的被調用的
obj = Demo()
obj()執(zhí)行結果:提示:‘Demo’ object is not callable ----- 沒有__call__方法

2.如果要類創(chuàng)建對象出來的對象可別調用,就要用到__call__方法
class Demo:
def __call__(self, *args,**kwds):
print("這是__call__方法執(zhí)行了")
print(callable(Demo))
# demo類創(chuàng)建出來的對象是否可被調用(不能被調用)
obj = Demo()
obj() # 等同于:obj.__call__() 方法
obj()
obj()
new 方法
__new__方法的作用 : 是創(chuàng)建對象的方法
__init__方法的作用 : 是用來初始化對象的方法
類的對象要能被調用:
首要new方法創(chuàng)建對象,然后通過init方法初始化
什么時候會需要用到New方法:
干預類實例化對象的過程
注意點:
- 一般情況不要重寫new方法,除非有特定的需求需要使用new方法來實現
- 定義了new方法之后,需要調用父類的new來創(chuàng)建對象 并返回
class MyTest(object):
# 初始化對象
def __init__(self):
print('-------init------方法')
# 創(chuàng)建對象
def __new__(cls, *args, **kwargs):
print('------new方法-------')
obj = super().__new__(cls) # 調用父類的new來創(chuàng)建對象
return obj # 并返回新的對象
obj = MyTest()bool(self)方法
定義當被 bool() 調用時的行為,應該返回 True 或 False
class Demo:
def __bool__(self):
"""內置函數bool(),獲取對象的布爾值是會執(zhí)行這個方法"""
return True
b = Demo()
# 獲取對象的布爾值,返回True 或 False
print(bool(b)) =====》 返回 Truestr(self)方法
使用print去輸出對象時,輸出到控制臺的內容是由__str__來決定的
class Demo:
def __str__(self):
"""
使用print去輸出對象時,輸出到控制臺的內容是由__str__來決定的
"""
return 'zifuc'
b = Demo()
# str方法
s = str('123')
print(s) =======》 返回 123repr(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)) =====》 返回 3hash(self)方法
返回對象的hash值
class Demo:
def __hash__(self):
"""
這個方法是獲取hash值
:return:
"""
return 999
b = Demo()
# 獲取hash值
print(hash(b)) =====》 返回 999二、python中容器類型的的魔術方法
setitem(self, key, value)方法
定義設置容器中指定元素的行為,語法:self[key] = value
class Mytest:
def __setitem__(self, key, value):
return setattr(self, key, value)
m = Mytest()
print(m.__dict__) 沒有數據,為空字典
m.name = 'gddg' ==== 》 設置name屬性,值為gddg
m['age'] = 18 ==== 》 設置age屬性,值為18getitem(self, item)方法
定義獲取容器中指定元素的行為,語法: self[key]
class Mytest:
def __getitem__(self,item):
return getattr(self,item)
m = Mytest()
print(m['name']) ==== 》 name屬性,值為gddgdelitem(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ā)的魔術方法"""
return True
a = MyTest()
b = MyTest()
print(a in b) =======》 返回 True迭代協(xié)議:__iter__方法
定義當迭代容器中的元素的行為
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中算數運算符的魔術方法
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)
對字符串對象沒有實現__sub__方法,所以不支持對象直接使用 -

自己在重新定義__sub__方法,實現對字符串對象的減法
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到此這篇關于python深入講解魔術方法的文章就介紹到這了,更多相關python魔術方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
tensorflow實現打印ckpt模型保存下的變量名稱及變量值
今天小編就為大家分享一篇tensorflow實現打印ckpt模型保存下的變量名稱及變量值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例
下面小編就為大家分享一篇用Python刪除本地目錄下某一時間點之前創(chuàng)建的所有文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12

