網(wǎng)站首頁 編程語言 正文
什么是魔術方法(魔法方法/特殊方法)
- 魔術方法都不需要手動去調(diào)用
- 是在特定的情況下觸發(fā)的
- 魔術方法都是在python事先定義好的,在定義方法的時候,不要使用魔術方法的命名規(guī)范
- 魔術方法是雙劃線開頭,雙劃線結尾的
一、python內(nèi)置的基本魔術方法
init方法
init 是類在實例化時的方法
# 例如
class Mytest():
def __init__(self):
print("----這是魔術方法__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í)行結果:提示:‘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)用時的行為,應該返回 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中容器類型的的魔術方法
setitem(self, key, value)方法
定義設置容器中指定元素的行為,語法: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' ==== 》 設置name屬性,值為gddg
m['age'] = 18 ==== 》 設置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ā)的魔術方法"""
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ù)運算符的魔術方法
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
原文鏈接:https://blog.csdn.net/qq_40236497/article/details/125411856
相關推薦
- 2022-10-14 DateUtil日期工具類
- 2022-08-26 Python?Matplotlib?marker?標記詳解_python
- 2022-08-29 Python常見異常處理總結_python
- 2023-03-28 Pytorch實現(xiàn)將label變成one?hot編碼的兩種方式_python
- 2022-07-03 Golang之理解錯誤輸出
- 2024-04-06 npm install安裝插件很慢,解決方法
- 2022-11-03 C#事件中關于sender的用法解讀_C#教程
- 2023-07-13 自定義設置echarts label里的顏色
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支