Python学习——02-Python基础——【9-面向对象进阶】——isinstance(obj,cls)、反射等...
一 isinstance(obj,cls)和issubclass(sub,super)
isinstance(obj,cls)檢查是否obj是否是類 cls 的對象
1 class Foo(object): 2 pass 3 4 obj = Foo() 5 6 isinstance(obj, Foo)?issubclass(sub, super)檢查sub類是否是 super 類的派生類
1 class Foo(object): 2 pass 3 4 class Bar(Foo): 5 pass 6 7 issubclass(Bar, Foo)二 反射
1 什么是反射
反射的概念是由Smith在1982年首次提出的,主要是指程序可以訪問、檢測和修改它本身狀態或行為的一種能力(自省)。這一概念的提出很快引發了計算機科學領域關于應用反射性的研究。它首先被程序語言的設計領域所采用,并在Lisp和面向對象方面取得了成績。
2 python面向對象中的反射:通過字符串的形式操作對象相關的屬性。python中的一切事物都是對象(都可以使用反射)
四個可以實現自省的函數
下列方法適用于類和對象(一切皆對象,類本身也是一個對象)
判斷object中有沒有一個name字符串對應的方法或屬性 hasattr(object,name) def getattr(object, name, default=None): # known special case of getattr"""getattr(object, name[, default]) -> valueGet a named attribute from an object; getattr(x, 'y') is equivalent to x.y.When a default argument is given, it is returned when the attribute doesn'texist; without it, an exception is raised in that case."""passgetattr(object, name, default=None) getattr(object, name, default=None) def setattr(x, y, v): # real signature unknown; restored from __doc__"""Sets the named attribute on the given object to the specified value.setattr(x, 'y', v) is equivalent to ``x.y = v''"""passsetattr(x, y, v) setattr(x, y, v) def delattr(x, y): # real signature unknown; restored from __doc__"""Deletes the named attribute from the given object.delattr(x, 'y') is equivalent to ``del x.y''"""passdelattr(x, y) delattr(x, y) class BlackMedium:feature='Ugly'def __init__(self,name,addr):self.name=nameself.addr=addrdef sell_house(self):print('%s 黑中介賣房子啦,傻逼才買呢,但是誰能證明自己不傻逼' %self.name)def rent_house(self):print('%s 黑中介租房子啦,傻逼才租呢' %self.name)b1=BlackMedium('萬成置地','回龍觀天露園')#檢測是否含有某屬性 print(hasattr(b1,'name')) print(hasattr(b1,'sell_house'))#獲取屬性 n=getattr(b1,'name') print(n) func=getattr(b1,'rent_house') func()# getattr(b1,'aaaaaaaa') #報錯 print(getattr(b1,'aaaaaaaa','不存在啊'))#設置屬性 setattr(b1,'sb',True) setattr(b1,'show_name',lambda self:self.name+'sb') print(b1.__dict__) print(b1.show_name(b1))#刪除屬性 delattr(b1,'addr') delattr(b1,'show_name') delattr(b1,'show_name111')#不存在,則報錯print(b1.__dict__)四個方法的使用演示 四個方法的使用演示 class Foo(object):staticField = "old boy"def __init__(self):self.name = 'wupeiqi'def func(self):return 'func'@staticmethoddef bar():return 'bar'print getattr(Foo, 'staticField') print getattr(Foo, 'func') print getattr(Foo, 'bar')類也是對象 類也是對象 #!/usr/bin/env python # -*- coding:utf-8 -*-import sysdef s1():print 's1'def s2():print 's2'this_module = sys.modules[__name__]hasattr(this_module, 's1') getattr(this_module, 's2')反射當前模塊成員 反射當前模塊成員?
?導入其他模塊,利用反射查找該模塊是否存在某個方法
#!/usr/bin/env python # -*- coding:utf-8 -*-def test():print('from the test') module_test.py #!/usr/bin/env python # -*- coding:utf-8 -*-""" 程序目錄:module_test.pyindex.py當前文件:index.py """import module_test as obj#obj.test()print(hasattr(obj,'test'))getattr(obj,'test')()?
?3 為什么用反射之反射的好處
好處一:實現可插拔機制
有倆程序員,一個lili,一個是egon,lili在寫程序的時候需要用到egon所寫的類,但是egon去跟女朋友度蜜月去了,還沒有完成他寫的類,lili想到了反射,使用了反射機制lili可以繼續完成自己的代碼,等egon度蜜月回來后再繼續完成類的定義并且去實現lili想要的功能。
總之反射的好處就是,可以事先定義好接口,接口只有在被完成后才會真正執行,這實現了即插即用,這其實是一種‘后期綁定’,什么意思?即你可以事先把主要的邏輯寫好(只定義接口),然后后期再去實現接口的功能
class FtpClient:'ftp客戶端,但是還么有實現具體的功能'def __init__(self,addr):print('正在連接服務器[%s]' %addr)self.addr=addr egon還沒有實現全部功能 #from module import FtpClient f1=FtpClient('192.168.1.1') if hasattr(f1,'get'):func_get=getattr(f1,'get')func_get() else:print('---->不存在此方法')print('處理其他的邏輯')不影響lili的代碼編寫 不影響lili的代碼編寫好處二:動態導入模塊(基于反射當前模塊成員)
?
三 __setattr__,__delattr__,__getattr__
class Foo:x=1def __init__(self,y):self.y=ydef __getattr__(self, item):print('----> from getattr:你找的屬性不存在')def __setattr__(self, key, value):print('----> from setattr')# self.key=value #這就無限遞歸了,你好好想想# self.__dict__[key]=value #應該使用它def __delattr__(self, item):print('----> from delattr')# del self.item #無限遞歸了self.__dict__.pop(item)#__setattr__添加/修改屬性會觸發它的執行 f1=Foo(10) print(f1.__dict__) # 因為你重寫了__setattr__,凡是賦值操作都會觸發它的運行,你啥都沒寫,就是根本沒賦值,除非你直接操作屬性字典,否則永遠無法賦值 f1.z=3 print(f1.__dict__)#__delattr__刪除屬性的時候會觸發 f1.__dict__['a']=3#我們可以直接修改屬性字典,來完成添加/修改屬性的操作 del f1.a print(f1.__dict__)#__getattr__只有在使用點調用屬性且屬性不存在的時候才會觸發 f1.xxxxxx三者的用法演示 三者的用法演示四 二次加工標準類型(包裝)
包裝:python為大家提供了標準數據類型,以及豐富的內置方法,其實在很多場景下我們都需要基于標準數據類型來定制我們自己的數據類型,新增/改寫方法,這就用到了我們剛學的繼承/派生知識(其他的標準類型均可以通過下面的方式進行二次加工)
class List(list): #繼承list所有的屬性,也可以派生出自己新的,比如append和middef append(self, p_object):' 派生自己的append:加上類型檢查'if not isinstance(p_object,int):raise TypeError('must be int')super().append(p_object)@propertydef mid(self):'新增自己的屬性'index=len(self)//2return self[index]l=List([1,2,3,4]) print(l) l.append(5) print(l) # l.append('1111111') #報錯,必須為int類型print(l.mid)#其余的方法都繼承list的 l.insert(0,-123) print(l) l.clear() print(l)二次加工標準類型(基于繼承實現) 二次加工標準類型(基于繼承實現) class List(list):def __init__(self,item,tag=False):super().__init__(item)self.tag=tagdef append(self, p_object):if not isinstance(p_object,str):raise TypeErrorsuper().append(p_object)def clear(self):if not self.tag:raise PermissionErrorsuper().clear()l=List([1,2,3],False) print(l) print(l.tag)l.append('saf') print(l)# l.clear() #異常 l.tag=True l.clear()練習(clear加權限限制) 練習(clear加權限限制)授權:授權是包裝的一個特性,?包裝一個類型通常是對已存在的類型的一些定制,這種做法可以新建,修改或刪除原有產品的功能。其它的則保持原樣。授權的過程,即是所有更新的功能都是由新類的某部分來處理,但已存在的功能就授權給對象的默認屬性。
實現授權的關鍵點就是覆蓋__getattr__方法
import time class FileHandle:def __init__(self,filename,mode='r',encoding='utf-8'):self.file=open(filename,mode,encoding=encoding)def write(self,line):t=time.strftime('%Y-%m-%d %T')self.file.write('%s %s' %(t,line))def __getattr__(self, item):return getattr(self.file,item)f1=FileHandle('b.txt','w+') f1.write('你好啊') f1.seek(0) print(f1.read()) f1.close()授權示范一 授權示范一 #_*_coding:utf-8_*_ __author__ = 'Linhaifeng' #我們來加上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=filenameself.mode=modeself.encoding=encodingdef 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.filenameelse: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,不用在進行encode轉成二進制去寫了,簡單,大氣 f1.write('你好啊'.encode('utf-8')) print(f1) f1.close()授權示范二 授權示范二 #練習一 class List:def __init__(self,seq):self.seq=seqdef append(self, p_object):' 派生自己的append加上類型檢查,覆蓋原有的append'if not isinstance(p_object,int):raise TypeError('must be int')self.seq.append(p_object)@propertydef mid(self):'新增自己的方法'index=len(self.seq)//2return self.seq[index]def __getattr__(self, item):return getattr(self.seq,item)def __str__(self):return str(self.seq)l=List([1,2,3]) print(l) l.append(4) print(l) # l.append('3333333') #報錯,必須為int類型print(l.mid)#基于授權,獲得insert方法 l.insert(0,-123) print(l)#練習二 class List:def __init__(self,seq,permission=False):self.seq=seqself.permission=permissiondef clear(self):if not self.permission:raise PermissionError('not allow the operation')self.seq.clear()def __getattr__(self, item):return getattr(self.seq,item)def __str__(self):return str(self.seq) l=List([1,2,3]) # l.clear() #此時沒有權限,拋出異常 l.permission=True print(l) l.clear() print(l)#基于授權,獲得insert方法 l.insert(0,-123) print(l)練習題(授權) 練習題(授權)五 __getattribute__
class Foo:def __init__(self,x):self.x=xdef __getattr__(self, item):print('執行的是我')# return self.__dict__[item] f1=Foo(10) print(f1.x) f1.xxxxxx #不存在的屬性訪問,觸發__getattr__ 回顧__getattr__ 回顧__getattr__ class Foo:def __init__(self,x):self.x=xdef __getattribute__(self, item):print('不管是否存在,我都會執行')f1=Foo(10) f1.x f1.xxxxxx__getattribute__ __getattribute__ #_*_coding:utf-8_*_ __author__ = 'Linhaifeng'class Foo:def __init__(self,x):self.x=xdef __getattr__(self, item):print('執行的是我')# return self.__dict__[item]def __getattribute__(self, item):print('不管是否存在,我都會執行')raise AttributeError('哈哈')f1=Foo(10) f1.x f1.xxxxxx#當__getattribute__與__getattr__同時存在,只會執行__getattrbute__,除非__getattribute__在執行過程中拋出異常AttributeError 二者同時出現 二者同時出現六 描述符(__get__,__set__,__delete__)
1 描述符是什么:描述符本質就是一個新式類,在這個新式類中,至少實現了__get__(),__set__(),__delete__()中的一個,這也被稱為描述符協議
__get__():調用一個屬性時,觸發
__set__():為一個屬性賦值時,觸發
__delete__():采用del刪除屬性時,觸發
2 描述符是干什么的:描述符的作用是用來代理另外一個類的屬性的(必須把描述符定義成這個類的類屬性,不能定義到構造函數中)
class Foo:def __get__(self, instance, owner):print('觸發get')def __set__(self, instance, value):print('觸發set')def __delete__(self, instance):print('觸發delete')#包含這三個方法的新式類稱為描述符,由這個類產生的實例進行屬性的調用/賦值/刪除,并不會觸發這三個方法 f1=Foo() f1.name='egon' f1.name del f1.name #疑問:何時,何地,會觸發這三個方法的執行 引子:描述符類產生的實例進行屬性操作并不會觸發三個方法的執行 引子:描述符類產生的實例進行屬性操作并不會觸發三個方法的執行 #描述符Str class Str:def __get__(self, instance, owner):print('Str調用')def __set__(self, instance, value):print('Str設置...')def __delete__(self, instance):print('Str刪除...')#描述符Int class Int:def __get__(self, instance, owner):print('Int調用')def __set__(self, instance, value):print('Int設置...')def __delete__(self, instance):print('Int刪除...')class People:name=Str()age=Int()def __init__(self,name,age): #name被Str類代理,age被Int類代理,self.name=nameself.age=age#何地?:定義成另外一個類的類屬性#何時?:且看下列演示 p1=People('alex',18)#描述符Str的使用 p1.name p1.name='egon' del p1.name#描述符Int的使用 p1.age p1.age=18 del p1.age#我們來瞅瞅到底發生了什么 print(p1.__dict__) print(People.__dict__)#補充 print(type(p1) == People) #type(obj)其實是查看obj是由哪個類實例化來的 print(type(p1).__dict__ == People.__dict__)描述符應用之何時?何地? 描述符應用之何時?何地?3 描述符分兩種
一 數據描述符:至少實現了__get__()和__set__()
二 非數據描述符:沒有實現__set__()
1 class Foo: 2 def __get__(self, instance, owner): 3 print('get')4 注意事項:
一 描述符本身應該定義成新式類,被代理的類也應該是新式類
二 必須把描述符定義成這個類的類屬性,不能為定義到構造函數中
三 要嚴格遵循該優先級,優先級由高到底分別是
1.類屬性
2.數據描述符
3.實例屬性
4.非數據描述符
5.找不到的屬性觸發__getattr__()
?
?
5 描述符使用
眾所周知,python是弱類型語言,即參數的賦值沒有類型限制,下面我們通過描述符機制來實現類型限制功能
class Str:def __init__(self,name):self.name=namedef __get__(self, instance, owner):print('get--->',instance,owner)return instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)class People:name=Str('name')def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryp1=People('egon',18,3231.3)#調用 print(p1.__dict__) p1.name#賦值 print(p1.__dict__) p1.name='egonlin' print(p1.__dict__)#刪除 print(p1.__dict__) del p1.name print(p1.__dict__)牛刀小試 牛刀小試 class Str:def __init__(self,name):self.name=namedef __get__(self, instance, owner):print('get--->',instance,owner)return instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)class People:name=Str('name')def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salary#疑問:如果我用類名去操作屬性呢 People.name #報錯,錯誤的根源在于類去操作屬性時,會把None傳給instance#修訂__get__方法 class Str:def __init__(self,name):self.name=namedef __get__(self, instance, owner):print('get--->',instance,owner)if instance is None:return selfreturn instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)class People:name=Str('name')def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salary print(People.name) #完美,解決 拔刀相助 拔刀相助 class Str:def __init__(self,name,expected_type):self.name=nameself.expected_type=expected_typedef __get__(self, instance, owner):print('get--->',instance,owner)if instance is None:return selfreturn instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)if not isinstance(value,self.expected_type): #如果不是期望的類型,則拋出異常raise TypeError('Expected %s' %str(self.expected_type))instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)class People:name=Str('name',str) #新增類型限制strdef __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryp1=People(123,18,3333.3)#傳入的name因不是字符串類型而拋出異常 磨刀霍霍 磨刀霍霍 class Typed:def __init__(self,name,expected_type):self.name=nameself.expected_type=expected_typedef __get__(self, instance, owner):print('get--->',instance,owner)if instance is None:return selfreturn instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)if not isinstance(value,self.expected_type):raise TypeError('Expected %s' %str(self.expected_type))instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)class People:name=Typed('name',str)age=Typed('name',int)salary=Typed('name',float)def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryp1=People(123,18,3333.3) p1=People('egon','18',3333.3) p1=People('egon',18,3333)大刀闊斧 大刀闊斧大刀闊斧之后我們已然能實現功能了,但是問題是,如果我們的類有很多屬性,你仍然采用在定義一堆類屬性的方式去實現,low,這時候我需要教你一招:獨孤九劍
def decorate(cls):print('類的裝飾器開始運行啦------>')return cls@decorate #無參:People=decorate(People) class People:def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryp1=People('egon',18,3333.3)類的裝飾器:無參 類的裝飾器:無參 def typeassert(**kwargs):def decorate(cls):print('類的裝飾器開始運行啦------>',kwargs)return clsreturn decorate @typeassert(name=str,age=int,salary=float) #有參:1.運行typeassert(...)返回結果是decorate,此時參數都傳給kwargs 2.People=decorate(People) class People:def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryp1=People('egon',18,3333.3)類的裝飾器:有參 類的裝飾器:有參終極大招
class Typed:def __init__(self,name,expected_type):self.name=nameself.expected_type=expected_typedef __get__(self, instance, owner):print('get--->',instance,owner)if instance is None:return selfreturn instance.__dict__[self.name]def __set__(self, instance, value):print('set--->',instance,value)if not isinstance(value,self.expected_type):raise TypeError('Expected %s' %str(self.expected_type))instance.__dict__[self.name]=valuedef __delete__(self, instance):print('delete--->',instance)instance.__dict__.pop(self.name)def typeassert(**kwargs):def decorate(cls):print('類的裝飾器開始運行啦------>',kwargs)for name,expected_type in kwargs.items():setattr(cls,name,Typed(name,expected_type))return clsreturn decorate @typeassert(name=str,age=int,salary=float) #有參:1.運行typeassert(...)返回結果是decorate,此時參數都傳給kwargs 2.People=decorate(People) class People:def __init__(self,name,age,salary):self.name=nameself.age=ageself.salary=salaryprint(People.__dict__) p1=People('egon',18,3333.3)刀光劍影 刀光劍影6 描述符總結
描述符是可以實現大部分python類特性中的底層魔法,包括@classmethod,@staticmethd,@property甚至是__slots__屬性
描述父是很多高級庫和框架的重要工具之一,描述符通常是使用到裝飾器或者元類的大型框架中的一個組件.
7 利用描述符原理完成一個自定制@property,實現延遲計算(本質就是把一個函數屬性利用裝飾器原理做成一個描述符:類的屬性字典中函數名為key,value為描述符類產生的對象)
class Room:def __init__(self,name,width,length):self.name=nameself.width=widthself.length=length@propertydef area(self):return self.width * self.lengthr1=Room('alex',1,1) print(r1.area)@property回顧 @property回顧 class Lazyproperty:def __init__(self,func):self.func=funcdef __get__(self, instance, owner):print('這是我們自己定制的靜態屬性,r1.area實際是要執行r1.area()')if instance is None:return selfreturn self.func(instance) #此時你應該明白,到底是誰在為你做自動傳遞self的事情class Room:def __init__(self,name,width,length):self.name=nameself.width=widthself.length=length@Lazyproperty #area=Lazyproperty(area) 相當于定義了一個類屬性,即描述符def area(self):return self.width * self.lengthr1=Room('alex',1,1) print(r1.area)自己做一個@property 自己做一個@property class Lazyproperty:def __init__(self,func):self.func=funcdef __get__(self, instance, owner):print('這是我們自己定制的靜態屬性,r1.area實際是要執行r1.area()')if instance is None:return selfelse:print('--->')value=self.func(instance)setattr(instance,self.func.__name__,value) #計算一次就緩存到實例的屬性字典中return valueclass Room:def __init__(self,name,width,length):self.name=nameself.width=widthself.length=length@Lazyproperty #area=Lazyproperty(area) 相當于'定義了一個類屬性,即描述符'def area(self):return self.width * self.lengthr1=Room('alex',1,1) print(r1.area) #先從自己的屬性字典找,沒有再去類的中找,然后出發了area的__get__方法 print(r1.area) #先從自己的屬性字典找,找到了,是上次計算的結果,這樣就不用每執行一次都去計算 實現延遲計算功能 實現延遲計算功能 #緩存不起來了class Lazyproperty:def __init__(self,func):self.func=funcdef __get__(self, instance, owner):print('這是我們自己定制的靜態屬性,r1.area實際是要執行r1.area()')if instance is None:return selfelse:value=self.func(instance)instance.__dict__[self.func.__name__]=valuereturn value# return self.func(instance) #此時你應該明白,到底是誰在為你做自動傳遞self的事情def __set__(self, instance, value):print('hahahahahah')class Room:def __init__(self,name,width,length):self.name=nameself.width=widthself.length=length@Lazyproperty #area=Lazyproperty(area) 相當于定義了一個類屬性,即描述符def area(self):return self.width * self.lengthprint(Room.__dict__) r1=Room('alex',1,1) print(r1.area) print(r1.area) print(r1.area) print(r1.area) #緩存功能失效,每次都去找描述符了,為何,因為描述符實現了set方法,它由非數據描述符變成了數據描述符,數據描述符比實例屬性有更高的優先級,因而所有的屬性操作都去找描述符了 一個小的改動,延遲計算的美夢就破碎了 一個小的改動,延遲計算的美夢就破碎了8 利用描述符原理完成一個自定制@classmethod
class ClassMethod:def __init__(self,func):self.func=funcdef __get__(self, instance, owner): #類來調用,instance為None,owner為類本身,實例來調用,instance為實例,owner為類本身,def feedback():print('在這里可以加功能啊...')return self.func(owner)return feedbackclass People:name='linhaifeng'@ClassMethod # say_hi=ClassMethod(say_hi)def say_hi(cls):print('你好啊,帥哥 %s' %cls.name)People.say_hi()p1=People() p1.say_hi() #疑問,類方法如果有參數呢,好說,好說class ClassMethod:def __init__(self,func):self.func=funcdef __get__(self, instance, owner): #類來調用,instance為None,owner為類本身,實例來調用,instance為實例,owner為類本身,def feedback(*args,**kwargs):print('在這里可以加功能啊...')return self.func(owner,*args,**kwargs)return feedbackclass People:name='linhaifeng'@ClassMethod # say_hi=ClassMethod(say_hi)def say_hi(cls,msg):print('你好啊,帥哥 %s %s' %(cls.name,msg))People.say_hi('你是那偷心的賊')p1=People() p1.say_hi('你是那偷心的賊')自己做一個@classmethod 自己做一個@classmethod9 利用描述符原理完成一個自定制的@staticmethod
class StaticMethod:def __init__(self,func):self.func=funcdef __get__(self, instance, owner): #類來調用,instance為None,owner為類本身,實例來調用,instance為實例,owner為類本身,def feedback(*args,**kwargs):print('在這里可以加功能啊...')return self.func(*args,**kwargs)return feedbackclass People:@StaticMethod# say_hi=StaticMethod(say_hi)def say_hi(x,y,z):print('------>',x,y,z)People.say_hi(1,2,3)p1=People() p1.say_hi(4,5,6)自己做一個@staticmethod 自己做一個@staticmethod?
?
六 再看property
一個靜態屬性property本質就是實現了get,set,delete三種方法
class Foo:@propertydef AAA(self):print('get的時候運行我啊')@AAA.setterdef AAA(self,value):print('set的時候運行我啊')@AAA.deleterdef AAA(self):print('delete的時候運行我啊')#只有在屬性AAA定義property后才能定義AAA.setter,AAA.deleter f1=Foo() f1.AAA f1.AAA='aaa' del f1.AAA用法一 用法一 class Foo:def get_AAA(self):print('get的時候運行我啊')def set_AAA(self,value):print('set的時候運行我啊')def delete_AAA(self):print('delete的時候運行我啊')AAA=property(get_AAA,set_AAA,delete_AAA) #內置property三個參數與get,set,delete一一對應 f1=Foo() f1.AAA f1.AAA='aaa' del f1.AAA用法二 用法二怎么用?
class Goods:def __init__(self):# 原價self.original_price = 100# 折扣self.discount = 0.8@propertydef price(self):# 實際價格 = 原價 * 折扣new_price = self.original_price * self.discountreturn new_price@price.setterdef price(self, value):self.original_price = value@price.deleterdef price(self):del self.original_priceobj = Goods() obj.price # 獲取商品價格 obj.price = 200 # 修改商品原價 print(obj.price) del obj.price # 刪除商品原價 案例一 案例一 #實現類型檢測功能#第一關: class People:def __init__(self,name):self.name=name@propertydef name(self):return self.name# p1=People('alex') #property自動實現了set和get方法屬于數據描述符,比實例屬性優先級高,所以你這面寫會觸發property內置的set,拋出異常#第二關:修訂版class People:def __init__(self,name):self.name=name #實例化就觸發property @propertydef name(self):# return self.name #無限遞歸print('get------>')return self.DouNiWan@name.setterdef name(self,value):print('set------>')self.DouNiWan=value@name.deleterdef name(self):print('delete------>')del self.DouNiWanp1=People('alex') #self.name實際是存放到self.DouNiWan里 print(p1.name) print(p1.name) print(p1.name) print(p1.__dict__)p1.name='egon' print(p1.__dict__)del p1.name print(p1.__dict__)#第三關:加上類型檢查 class People:def __init__(self,name):self.name=name #實例化就觸發property @propertydef name(self):# return self.name #無限遞歸print('get------>')return self.DouNiWan@name.setterdef name(self,value):print('set------>')if not isinstance(value,str):raise TypeError('必須是字符串類型')self.DouNiWan=value@name.deleterdef name(self):print('delete------>')del self.DouNiWanp1=People('alex') #self.name實際是存放到self.DouNiWan里 p1.name=1案例二 案例二七 __setitem__,__getitem,__delitem__
class Foo:def __init__(self,name):self.name=namedef __getitem__(self, item):print(self.__dict__[item])def __setitem__(self, key, value):self.__dict__[key]=valuedef __delitem__(self, key):print('del obj[key]時,我執行')self.__dict__.pop(key)def __delattr__(self, item):print('del obj.key時,我執行')self.__dict__.pop(item)f1=Foo('sb') f1['age']=18 f1['age1']=19 del f1.age1 del f1['age'] f1['name']='alex' print(f1.__dict__) View Code八 __str__,__repr__,__format__
改變對象的字符串顯示__str__,__repr__
自定制格式化字符串__format__
#_*_coding:utf-8_*_ __author__ = 'Linhaifeng' format_dict={'nat':'{obj.name}-{obj.addr}-{obj.type}',#學校名-學校地址-學校類型'tna':'{obj.type}:{obj.name}:{obj.addr}',#學校類型:學校名:學校地址'tan':'{obj.type}/{obj.addr}/{obj.name}',#學校類型/學校地址/學校名 } class School:def __init__(self,name,addr,type):self.name=nameself.addr=addrself.type=typedef __repr__(self):return 'School(%s,%s)' %(self.name,self.addr)def __str__(self):return '(%s,%s)' %(self.name,self.addr)def __format__(self, format_spec):# if format_specif not format_spec or format_spec not in format_dict:format_spec='nat'fmt=format_dict[format_spec]return fmt.format(obj=self)s1=School('oldboy1','北京','私立') print('from repr: ',repr(s1)) print('from str: ',str(s1)) print(s1)''' str函數或者print函數--->obj.__str__() repr或者交互式解釋器--->obj.__repr__() 如果__str__沒有被定義,那么就會使用__repr__來代替輸出 注意:這倆方法的返回值必須是字符串,否則拋出異常 ''' print(format(s1,'nat')) print(format(s1,'tna')) print(format(s1,'tan')) print(format(s1,'asfdasdffd')) View Code date_dic={'ymd':'{0.year}:{0.month}:{0.day}','dmy':'{0.day}/{0.month}/{0.year}','mdy':'{0.month}-{0.day}-{0.year}', } class Date:def __init__(self,year,month,day):self.year=yearself.month=monthself.day=daydef __format__(self, format_spec):if not format_spec or format_spec not in date_dic:format_spec='ymd'fmt=date_dic[format_spec]return fmt.format(self)d1=Date(2016,12,29) print(format(d1)) print('{:mdy}'.format(d1))自定義format練習 自定義format練習 #_*_coding:utf-8_*_ __author__ = 'Linhaifeng'class A:passclass B(A):passprint(issubclass(B,A)) #B是A的子類,返回True a1=A() print(isinstance(a1,A)) #a1是A的實例 issubclass和isinstance issubclass和isinstance九 __slots__
''' 1.__slots__是什么:是一個類變量,變量值可以是列表,元祖,或者可迭代對象,也可以是一個字符串(意味著所有實例只有一個數據屬性) 2.引子:使用點來訪問屬性本質就是在訪問類或者對象的__dict__屬性字典(類的字典是共享的,而每個實例的是獨立的) 3.為何使用__slots__:字典會占用大量內存,如果你有一個屬性很少的類,但是有很多實例,為了節省內存可以使用__slots__取代實例的__dict__ 當你定義__slots__后,__slots__就會為實例使用一種更加緊湊的內部表示。實例通過一個很小的固定大小的數組來構建,而不是為每個實例定義一個 字典,這跟元組或列表很類似。在__slots__中列出的屬性名在內部被映射到這個數組的指定小標上。使用__slots__一個不好的地方就是我們不能再給 實例添加新的屬性了,只能使用在__slots__中定義的那些屬性名。 4.注意事項:__slots__的很多特性都依賴于普通的基于字典的實現。另外,定義了__slots__后的類不再 支持一些普通類特性了,比如多繼承。大多數情況下,你應該 只在那些經常被使用到 的用作數據結構的類上定義__slots__比如在程序中需要創建某個類的幾百萬個實例對象 。 關于__slots__的一個常見誤區是它可以作為一個封裝工具來防止用戶給實例增加新的屬性。盡管使用__slots__可以達到這樣的目的,但是這個并不是它的初衷。 更多的是用來作為一個內存優化工具。''' class Foo:__slots__='x'f1=Foo() f1.x=1 f1.y=2#報錯 print(f1.__slots__) #f1不再有__dict__class Bar:__slots__=['x','y']n=Bar() n.x,n.y=1,2 n.z=3#報錯__slots__使用 __slots__使用 class Foo:__slots__=['name','age']f1=Foo() f1.name='alex' f1.age=18 print(f1.__slots__)f2=Foo() f2.name='egon' f2.age=19 print(f2.__slots__)print(Foo.__dict__) #f1與f2都沒有屬性字典__dict__了,統一歸__slots__管,節省內存 刨根問底 刨根問底十 __next__和__iter__實現迭代器協議
#_*_coding:utf-8_*_ __author__ = 'Linhaifeng' class Foo:def __init__(self,x):self.x=xdef __iter__(self):return selfdef __next__(self):n=self.xself.x+=1return self.xf=Foo(3) for i in f:print(i)簡單示范 簡單示范 class Foo:def __init__(self,start,stop):self.num=startself.stop=stopdef __iter__(self):return selfdef __next__(self):if self.num >= self.stop:raise StopIterationn=self.numself.num+=1return nf=Foo(1,5) from collections import Iterable,Iterator print(isinstance(f,Iterator))for i in Foo(1,5):print(i) class Range:def __init__(self,n,stop,step):self.n=nself.stop=stopself.step=stepdef __next__(self):if self.n >= self.stop:raise StopIterationx=self.nself.n+=self.stepreturn xdef __iter__(self):return selffor i in Range(1,7,3): # print(i)練習:簡單模擬range,加上步長 練習:簡單模擬range,加上步長 class Fib:def __init__(self):self._a=0self._b=1def __iter__(self):return selfdef __next__(self):self._a,self._b=self._b,self._a + self._breturn self._af1=Fib()print(f1.__next__()) print(next(f1)) print(next(f1))for i in f1:if i > 100:breakprint('%s ' %i,end='')斐波那契數列 斐波那契數列?
?參考:http://www.cnblogs.com/linhaifeng/articles/6204014.html#_label6
轉載于:https://www.cnblogs.com/caofu/p/8762641.html
總結
以上是生活随笔為你收集整理的Python学习——02-Python基础——【9-面向对象进阶】——isinstance(obj,cls)、反射等...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: netty为什么性能高
- 下一篇: volatile不具备原子性