日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python深入講解魔術方法_python

作者:henry_rhy ? 更新時間: 2022-08-20 編程語言

什么是魔術方法(魔法方法/特殊方法)

  • 魔術方法都不需要手動去調(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

欄目分類
最近更新