第8天崔赌,面向?qū)ο筮M(jìn)階
@(python)[筆記]
目錄
一械拍、isinstance()和issubclass()
1. isinstance()
2. issubclass()
二、反射
1. hasattr()
2. getattr()
3. setattr()
4. delattr()
5. 擴(kuò)展用法
三涮因、__setattr__废睦、__delattr__、__getattr__
四养泡、二次加工標(biāo)準(zhǔn)類型(包裝)
授權(quán)
五嗜湃、__next__和__iter__實(shí)現(xiàn)迭代器協(xié)議
六、__doc__
七澜掩、__module__和__class__
八购披、__str__
九、__del__析構(gòu)方法
十肩榕、__setitem__,__getitem__,__delitem__
十一刚陡、__enter__和__exit__
十二、__call__
十三株汉、元類metaclass
先來看看exec
未完
一筐乳、isinstance()和issubclass()
1. isinstance()
語法:isinstance(obj,cls)
功能:檢查對(duì)象obj是否是類cls的實(shí)例
class foo:
pass
obj = foo()
print(isinstance(obj,foo)) #True
2. issubclass()
語法:issubclass(sub, super)
功能:檢查sub類是否是super類的派生類(子類)
class foo:
pass
obj = foo()
print(isinstance(obj,foo)) #True
class bar(foo):
pass
print(issubclass(bar,foo)) #True
二、反射
反射主要是指程序可以訪問乔妈、檢測(cè)和修改它本身狀態(tài)或行為的一種能力蝙云,也可以稱為自省。
python面向?qū)ο笾械姆瓷涫侵竿ㄟ^字符串的形式操作對(duì)象相關(guān)的屬性路召。python中的一切事物都是對(duì)象勃刨,都可以使用反射。
python中可以實(shí)現(xiàn)自省的四個(gè)函數(shù):
下列方法適用于類和對(duì)象(一切皆對(duì)象股淡,類本身也是一個(gè)對(duì)象)
1. hasattr()
語法:hasattr(object,"name")
功能:判斷object中有沒有一個(gè)name字符串對(duì)應(yīng)的方法或?qū)傩浴?br>
用法:
class foo:
name = "egon"
pass
obj = foo()
print(hasattr(obj,"name")) #True
print(hasattr(obj,"func")) #True
print(hasattr(foo,"name")) #True
print(hasattr(foo,"func")) #True
2. getattr()
語法:getattr(object, "name"[, default=None])
功能:從對(duì)象object獲取一個(gè)name字符串對(duì)應(yīng)的方法身隐,如果沒有name字符串對(duì)應(yīng)的方法,并且沒有設(shè)置default揣非,則報(bào)錯(cuò)抡医;如果沒有name字符串對(duì)應(yīng)的方法,設(shè)置了default早敬,則將default的值返回忌傻。getattr(object,"name")
等價(jià)于object.name
class foo:
name = "egon"
def func(self):
print("Hello world")
obj = foo()
print(getattr(obj,"func"))
#<bound method foo.func of <__main__.foo object at 0x000000000112ACC0>>
#可以看出,輸出結(jié)果是一個(gè)綁定方法
f1 = getattr(obj,"func")
f2 = getattr(obj,"bar","不存在")
f1() #Hello world
print(f2) #不存在
3. setattr()
語法:setattr(x, y, v)
功能:設(shè)置屬性搞监,setattr(x水孩,'y',v)
等價(jià)于“x.y = v
”
用法:
class foo:
name = "egon"
def func(self):
print("Hello world")
obj = foo()
setattr(obj,"age",20)
setattr(obj,"show_name",lambda self:self.name+"_NB")
print(obj.__dict__) #查看屬性字典
print(obj.show_name(obj))
'''
輸出:
{'age': 20, 'show_name': <function <lambda> at 0x000000000115E2F0>}
egon_NB
'''
4. delattr()
語法:delattr(x, y)
功能:刪除屬性,delattr(x琐驴,'y')
相當(dāng)于```del x.y`''
用法:
delattr(obj,"show_name")
# delattr(obj,"sex") #不存在俘种,則報(bào)錯(cuò)
print(obj.__dict__) #{'age': 20}
5. 擴(kuò)展用法
反射當(dāng)前模塊
import sys
def s1():
print("s1")
def s2():
print("s2")
this_module = sys.modules[__name__]
print(hasattr(this_module,"s1")) #True
print(getattr(this_module,"s2"))
#<function s2 at 0x00000000006EE378>,加括號(hào)可執(zhí)行
導(dǎo)入其他模塊秤标,利用反射查找該模塊是否存在某個(gè)方法
程序目錄:
- module_test.py
- current.py
# module_test.py
def test():
print("from the module_test.test")
#current.py
import module_test as mt
print(hasattr(mt,"test")) #True
f = getattr(mt,"test","不存在")
f() #from the module_test.test
三、__setattr__
宙刘、__delattr__
苍姜、__getattr__
__setattr__
:添加/修改屬性會(huì)觸發(fā)它的執(zhí)行;
__delattr__
:刪除屬性的時(shí)候會(huì)觸發(fā)悬包;
__getattr__
:只有在使用點(diǎn)調(diào)用屬性且屬性不存在的時(shí)候才會(huì)觸發(fā)衙猪。
class Foo:
x = 1
def __init__(self,y):
self.y = y
def __getattr__(self, item):
print("---> 你找的屬性不存在")
def __setattr__(self, key, value):
print("---> from __setattr__")
# self.key = value #這樣會(huì)陷入無限遞歸,只能通過__dict__字典進(jìn)行賦值
self.__dict__[key] = value #這樣才可以正確賦值
def __delattr__(self, item):
print("---> from __delattr__")
f1 = Foo(10) #相當(dāng)于設(shè)值布近,觸發(fā)__setattr__執(zhí)行垫释,---> from __setattr__
print(f1.__dict__)
#{},直接打印為空撑瞧,是因?yàn)槟阕约褐貙懥薩_setattr__方法棵譬,
# 而你在__setattr__方法中沒有真正賦值
f1.z #觸發(fā)__getattr__執(zhí)行,---> 你找的屬性不存在
del f1.x #觸發(fā)__delattr__執(zhí)行预伺,---> from __delattr__
四订咸、二次加工標(biāo)準(zhǔn)類型(包裝)
包裝:python為用戶提供了標(biāo)準(zhǔn)數(shù)據(jù)類型,以及豐富的內(nèi)置方法扭屁,其在很多場(chǎng)景下算谈,我們需要基于標(biāo)準(zhǔn)數(shù)據(jù)類型來定制我們自己的數(shù)據(jù)類型涩禀,新增 / 改寫方法料滥,這就用到繼承和派生的知識(shí),其他標(biāo)準(zhǔn)類型均可以通過下面的方式進(jìn)行二次加工艾船。
示例1:對(duì)list
進(jìn)行二次加工葵腹,限制append只能增加int
整型數(shù)據(jù);并且增加mid
方法屿岂,得到列表的中間值践宴;其余方法都繼承list
的。
class List(list):
def append(self,p_object):
#派生出自己的append方法爷怀,會(huì)覆蓋父類list中的append方法
if not isinstance(p_object,int):
raise TypeError("%s must be int"%p_object)
super(List, self).append(p_object)
@property
#中間值聽起來更像一個(gè)屬性阻肩,而非方法,所以使用property
def mid(self):
mid_num = len(self) // 2
return self[mid_num]
l = List([1,2,3,4])
print(l) #[1, 2, 3, 4]
l.append(5)
print(l) #[1, 2, 3, 4, 5]
print(l.mid) #中間值3
示例二:為list
的clear
方法增加權(quán)限
class List(list):
def __init__(self,item,perm=False):
super(List, self).__init__(item)
self.perm = perm
#先設(shè)定一個(gè)默認(rèn)的權(quán)限
def clear(self):
if not self.perm:
raise PermissionError("權(quán)限拒絕")
super(List, self).clear()
l = List([1,2,3])
print(l) #[1, 2, 3]
# l.clear() #拋出“權(quán)限拒絕”的異常
l = List([1,2,3],True) #給一個(gè)授權(quán)參數(shù)為True
l.clear()
print(l) #[]运授,可以正常清空列表
授權(quán)
授權(quán)是包裝的一個(gè)特性烤惊,包裝一個(gè)類型通常是對(duì)已存在的類型的一些定制,這種做法可以新建吁朦、修改或刪除原有產(chǎn)品的功能柒室,其它的則保持原樣。授權(quán)的過程就是所有更新的功能都是由新類的某部分來處理逗宜,但已存在的功能就授權(quán)給對(duì)象的默認(rèn)屬性雄右。
實(shí)現(xiàn)授權(quán)的關(guān)鍵點(diǎn)就是覆蓋__getattr__
方法
示例三:利用open()
函數(shù)重新定制一個(gè)文件處理器空骚,增加寫內(nèi)容添加時(shí)間的功能;
import time
class FileHandler:
def __init__(self,filename,mode='r',encoding="utf-8"):
self.file = open(filename,mode,encoding=encoding)
#self.file獲取到一個(gè)文件句柄
def write(self,line):
t = time.strftime("%Y-%m-%d %X")
self.file.write("%s %s"%(t,line))
def __getattr__(self, item):
return getattr(self.file,item)
#當(dāng)對(duì)象調(diào)用FileHandler類不存在的方法時(shí)擂仍,會(huì)返回open()函數(shù)的item字符串對(duì)應(yīng)的方法囤屹;
f1 = FileHandler("a.txt","r+")
f1.write("你好嗎\n")
f1.seek(0)
print(f1.tell()) #0
示例四:
#我們來加上b模式支持
import time
class FileHandle:
def __init__(self,filename,mode='r',encoding='utf-8'):
if 'b' in mode:
self.file=open(filename,mode)
else:
self.file=open(filename,mode,encoding=encoding)
self.filename=filename
self.mode=mode
self.encoding=encoding
def write(self,line):
if 'b' in self.mode:
if not isinstance(line,bytes):
raise TypeError('must be bytes')
self.file.write(line)
def __getattr__(self, item):
return getattr(self.file,item)
def __str__(self):
if 'b' in self.mode:
res="<_io.BufferedReader name='%s'>" %self.filename
else:
res="<_io.TextIOWrapper name='%s' mode='%s' encoding='%s'>" %(self.filename,self.mode,self.encoding)
return res
f1=FileHandle('b.txt','wb')
# f1.write('你好啊啊啊啊啊') #自定制的write,不用在進(jìn)行encode轉(zhuǎn)成二進(jìn)制去寫了,簡(jiǎn)單,大氣
f1.write('你好啊'.encode('utf-8'))
print(f1)
f1.close()
示例五:利用授權(quán)的方式重新定制list
的append
方法,只能往列表中添加int
整型數(shù)據(jù)逢渔;與示例一作對(duì)比牺丙,看一下兩者的區(qū)別。
#授權(quán)复局,定制list
class List:
def __init__(self,seq):
self.seq = list(seq)
def append(self,p_object):
if not isinstance(p_object,int):
raise TypeError("'%s' must be int"%p_object)
self.seq.append(p_object)
def __getattr__(self, item):
return getattr(self.seq,item)
def __str__(self):
return str(self.seq)
l = List([1,2,3])
l.append("4") #TypeError: '4' must be int
print(l)
總結(jié):授權(quán)這種方式用在定制源不是類的情況下冲簿。例如示例三中,定制
open()
函數(shù)
五亿昏、__next__
和__iter__
實(shí)現(xiàn)迭代器協(xié)議
迭代器必須要有__next__
和__iter__
方法峦剔;
現(xiàn)在就來自己實(shí)現(xiàn)一個(gè)迭代器吧;
簡(jiǎn)單實(shí)現(xiàn):
class Foo:
def __init__(self,x):
self.x=x
def __iter__(self):
return self
def __next__(self):
n=self.x
self.x+=1
return self.x
f=Foo(3)
for i in f:
print(i)
模擬實(shí)現(xiàn)range()函數(shù):
class foo:
def __init__(self,start,stop=None,step=1):
self.start = start
self.stop = stop
self.step = step
if isinstance(self.start,str) \
or isinstance(self.stop,str) \
or isinstance(self.step,str):
raise InterruptedError("Must be Numeric")
def __next__(self):
if self.stop:
res = self.compute()
else:
self.stop = self.start
# 如果只傳了一個(gè)數(shù)字,則將其設(shè)為迭代停止數(shù)字
self.start = 0
# 如果只傳了一個(gè)數(shù)字角钩,則默認(rèn)從0開始迭代
res = self.compute()
return res
def __iter__(self):
return self
#迭代器執(zhí)行__iter__方法吝沫,返回的是它本身
def compute(self):
if self.start >= self.stop:
#判斷是否超出迭代停止數(shù)字
raise StopIteration
# 這是超出迭代器范圍后迭代器協(xié)議規(guī)定的拋出異常
iter_val = self.start #迭代后的值
self.start += self.step
return iter_val
for i in foo('a',20,3.5):
print(i)
for i in foo(5,15,3):
print(i)
六、__doc__
查看對(duì)象的描述信息
def func():
'''我是函數(shù)的描述信息'''
pass
print(func.__doc__)
class Foo:
'''我是類的描述信息'''
pass
class bar(Foo):
pass
obj = Foo()
print(obj.__doc__)
print(Foo.__doc__)
print(bar.__doc__) #該屬性不會(huì)繼承給子類
'''
輸出:
我是函數(shù)的描述信息
我是類的描述信息
我是類的描述信息
None
'''
七递礼、__module__
和__class__
__module__
表示當(dāng)前操作的對(duì)象在那個(gè)模塊
__class__
表示當(dāng)前操作的對(duì)象的類是什么
以下兩個(gè)文件在同一級(jí)目錄下:
#current.py
class C:
def __init__(self):
self.name = "alex"
#test.py
import current
def test():
print("from the test.test")
obj = current.C()
print(obj.name)
print(obj.__class__) #輸出是哪個(gè)類實(shí)例化得到的對(duì)象
print(obj.__module__) #輸出屬性哪個(gè)模塊
'''
輸出:
alex
<class 'current.C'>
current
'''
八惨险、__str__
l = list([1,2,3])
print(l) #打印的是[1, 2, 3]
class mysql:
def __init__(self,host,port):
self.host = host
self.port = port
conn = mysql("127.0.0.1","3306")
print(conn) #打印的是<__main__.mysql object at 0x0000000000701898>
從以上兩段代碼可以看到,我們自己定義的類脊髓,生成的對(duì)象直接被打印時(shí)辫愉,打印的是對(duì)象的內(nèi)存地址,而這并不是我們想要的将硝,我們實(shí)際想要的也是像第一段代碼那樣返回一個(gè)有用的信息恭朗,這時(shí)就要用到__str__
這個(gè)內(nèi)置方法了,它定義在類的內(nèi)部依疼,只要類被實(shí)例化痰腮,就會(huì)自動(dòng)觸發(fā)__str__
的執(zhí)行,并返回一個(gè)值給實(shí)例化后的對(duì)象律罢。如下示例:
class mysql:
def __init__(self,host,port):
self.host = host
self.port = port
def __str__(self):
return "Host:%s,Port:%s"%(self.host,self.port)
conn = mysql("127.0.0.1","3306")
#會(huì)將`__str__`方法的返回值賦值給對(duì)象conn
print(conn)
'''
輸出:
Host:127.0.0.1,Port:3306
'''
九膀值、__del__
析構(gòu)方法
析構(gòu)方法,當(dāng)對(duì)象在內(nèi)存中被釋放時(shí)误辑,會(huì)自動(dòng)觸發(fā)__del__
執(zhí)行沧踏。
注:此方法一般無須定義,因?yàn)镻ython是一門高級(jí)語言稀余,程序員在使用時(shí)無需關(guān)心內(nèi)存的分配和釋放悦冀,因?yàn)榇斯ぷ鞫际墙唤oPython解釋器來執(zhí)行,所以睛琳,析構(gòu)函數(shù)的調(diào)用是由解釋器在進(jìn)行垃圾回收時(shí)自動(dòng)觸發(fā)執(zhí)行的盒蟆。
簡(jiǎn)單示例:
class Foo:
def __del__(self):
print("執(zhí)行__del__")
f1 = Foo()
del f1 #釋放f1踏烙,會(huì)觸發(fā)__del__執(zhí)行
print("------->")
'''
輸出:
執(zhí)行__del__
------->
'''
再看看下面這種情況:
class Foo:
def __del__(self):
print("執(zhí)行__del__")
f1 = Foo()
# del f1 #注釋掉
print("------->")
'''
輸出:
------->
執(zhí)行__del__
'''
#可以看出__del__仍然會(huì)在程序執(zhí)行完畢后,被觸發(fā)執(zhí)行
十历等、__setitem__
,__getitem__
,__delitem__
類中有這三個(gè)方法讨惩,那就意味著類中的屬性可以像字典一樣進(jìn)行操作;
class Foo:
def __init__(self,name):
self.name = name
def __getitem__(self, item):
print("from __getitem__")
def __setitem__(self, key, value):
print("from __setitem__")
self.__dict__[key] = value #加入此代碼寒屯,才會(huì)真正設(shè)值
def __delitem__(self, key):
print("from __delitem__")
self.__dict__.pop(key)
f1 = Foo("egon")
# f1.age = 18 #不會(huì)觸發(fā)__setitem__的執(zhí)行
f1["age_2"] = 20 #會(huì)觸發(fā)__setitem__的執(zhí)行荐捻,并不會(huì)真正設(shè)值;
print(f1.__dict__)
del f1["age_2"]
print(f1.__dict__)
print(f1["name"]) #會(huì)觸發(fā)__getitem__執(zhí)行寡夹,如果__getitem__沒有設(shè)定返回值处面,則會(huì)返回一個(gè)None
'''
輸出結(jié)果:
from __setitem__
{'name': 'egon', 'age_2': 20}
from __delitem__
{'name': 'egon'}
from __getitem__
None
'''
#從結(jié)果可以看出,age_2 = 20并沒有真正設(shè)值成功
十一菩掏、__enter__
和__exit__
通過__enter__
和__exit__
這兩個(gè)方法可以實(shí)現(xiàn)上下文件管理協(xié)議魂角,即with
語句。為了讓一個(gè)對(duì)象兼容with
語句智绸,必須在這個(gè)對(duì)象的類中聲明__enter__
和__exit__
方法野揪。
class Open:
def __init__(self,name):
self.name = name
def __enter__(self):
#出現(xiàn)with語句,對(duì)象的__enter__方法就會(huì)被觸發(fā)瞧栗,有返回值則賦值給as聲明的變量
print("from __enter__")
return 3 #會(huì)返回給as語句后面的變量
def __exit__(self, exc_type, exc_val, exc_tb):
print("from __exit__, with代碼塊執(zhí)行完畢時(shí)觸發(fā)")
with Open("egon") as f:
print("from with 代碼塊")
print("f:",f)
'''
輸出:
from __enter__
from with 代碼塊
f: 3
from __exit__, with代碼塊執(zhí)行完畢時(shí)觸發(fā)
'''
__exit__(self, exc_type, exc_val, exc_tb)
中的三個(gè)參數(shù)的含義:
-
exc_type
代表異常類型 -
exc_val
代表異常值 -
exc_tb
代表異常的追溯信息
class Open:
def __init__(self,name):
self.name = name
def __enter__(self):
#出現(xiàn)with語句斯稳,對(duì)象的__enter__方法就會(huì)被觸發(fā),有返回值則賦值給as聲明的變量
# print("from __enter__")
return self #會(huì)返回給as語句后面的變量
def __exit__(self, exc_type, exc_val, exc_tb):
print("from __exit__, with代碼塊執(zhí)行完畢時(shí)觸發(fā)")
print("exc_type:",exc_type)
print("exc_val:",exc_val)
print("exc_tb:",exc_tb)
return True #返回True,則表示不拋出異常迹恐,with代碼之后的代碼可正常執(zhí)行挣惰,但with子代碼raise后的代碼不會(huì)執(zhí)行。
with Open("egon") as f:
print("from with 代碼塊")
raise AttributeError("屬性錯(cuò)誤")
# print("=====> 在異常之后") #不會(huì)執(zhí)行
print("=====> 在異常之后系草,with之外") #__exit__返回True才會(huì)執(zhí)行
'''
輸出:
from with 代碼塊
from __exit__, with代碼塊執(zhí)行完畢時(shí)觸發(fā)
exc_type: <class 'AttributeError'>
exc_val: 屬性錯(cuò)誤
exc_tb: <traceback object at 0x014B58A0>
=====> 在異常之后
'''
示例:模擬open()通熄,并實(shí)現(xiàn)上下文管理
#模擬open()功能
class Open:
def __init__(self,filename,mode='r',encoding="utf-8"):
self.filename = filename
self.mode = mode
self.encoding = encoding
def __enter__(self):
self.file = open(self.filename,self.mode,encoding =self.encoding)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
return True #遇到異常不拋出唆涝,with之外的代碼繼續(xù)執(zhí)行
with Open("a.txt","w+") as f:
f.write("11111\n")
f.write("22222\n")
f.seek(0)
print(f.tell())
f.abc #拋出異常找都,交給__exit__處理
十二、__call__
對(duì)象后面加括號(hào)廊酣,就會(huì)觸發(fā)__call__
方法的執(zhí)行能耻;反之類中有了__call__
方法,通過這個(gè)類生成的對(duì)象亡驰,才能加括號(hào)執(zhí)行晓猛。
class foo:
def __init__(self):
print("from __init__")
def __call__(self, *args, **kwargs):
print("from __call__")
obj = foo() #執(zhí)行__init__
obj() #執(zhí)行__call__
'''
輸出:
from __init__
from __call__
'''