isinstance和issubclass
# isinstance(obj,cls) 檢查obj是否是類cls的對象class Foo:def __init__(self,name):self.name = nameclass Clss: def __init__(self,name):self.name = namesb = Foo('ssb')print(isinstance(sb, Foo)) # 判斷sb是否是Foo的對象sc = Clss('ak')print(isinstance(sc, Foo)) # 判斷sc是否是Foo的對象# 返回值# True# False
# issubclass(sub, super)檢查sub類是否是super的派生類classFoo:def __init__(self):passclass Sb(Foo): def __init__(self): passprint(issubclass(Sb, Foo)) # 判斷Sb是否是Foo的子類# 結果# True
反射
反射定義:反射的概念是由Smith在1982年首次提出的,主要是指程序可以訪問、檢測和修改它本身狀態或行為的一種能力(自省)。這一概念的提出很快引發了計算機科學領域關於應用反射性的研究。它首先被程序語言的設計領域所採用,並在Lisp和面向對象方面取得了成績。
python面向對象中的反射:通過字符串的形式操作對象相關屬性.python中的一切事物都是對象(都可以使用反射)
四個可以實現自省的函數
下列方法適用類和對象(一切皆對象,類本身也是一個對象)
hasattr
defhasattr(*args, **kwargs):# real signature unknown""" Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
getattr
def getattr(object, name, default=None): # known special case of getattr"""getattr(object, name[, default]) -> value Get 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't exist; without it, an exception is raised in that case. """ pass
setattr
defsetattr(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'' """ pass
delattr
defdelattr(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'' """ pass
四方法演示
1 class Foo:2 f = 'abc' # 類的靜態變量3 def __init__(self, name, pwd):4 self.name = name5 self.pwd = pwd6 def exex(self):7print('hi {}'.format(self.name))8return'ssd'9 class Ak:10 f = 'ssd'11 def __init__(self):12 pass13 sb = Foo('張飛', 38)14 ak = Ak()1516 # hasattr檢查是否含有某些屬性1718print(hasattr(sb, 'name')) # 檢查對象sb中是否含所有name屬性 屬性名以字符串形式顯示19print(hasattr(ak, 'name')) # 檢查對象ak中是否含所有name屬性 屬性名以字符串形式顯示20 # 結果21 # True22 # False23 24 # getattr獲取屬性 有此對象屬性就輸出沒有就報錯,可以定製報錯形式,使其不報錯2526print(getattr(sb, 'name')) # 獲取對象的屬性 getattr函數 括號第一位填對象 第二位填屬性27print(getattr(sb, 'exex')) # 獲取動態屬性28print(getattr(sb,'exex')()) # 加括號可以直接調用29 # print(getattr(sb,'rr')) # 如果沒有此屬性將報錯30print(getattr(sb,'rr','不存在')) # 如果沒有此屬性將報錯 可以定製報錯形式使其不報錯3132 # setattr設置屬性 原則:如果原本含有此屬性便修改其屬性,如果不存在此屬性,便添加此屬性3334 setattr(sb, 'sb', 27) # 為對象sb增加屬性 屬性名為sb 屬性值為2735print(sb.__dict__)36 # 結果 {'name': '張飛', 'pwd': 38, 'sb': 27}37 setattr(sb, 'ak117', 38) # 為對象sb增加屬性 屬性名為ak117 屬性值為3838print(sb.__dict__)39 # 結果:{'name': '張飛', 'pwd': 38, 'sb': 27, 'ak117': 38}40 setattr(sb, 'ak117', 39) # 對對象sb修改屬性 將屬性為ak117的屬性值修改為3941print(sb.__dict__)42 # 結果 {'name': '張飛', 'pwd': 38, 'sb': 27, 'ak117': 39}43 setattr(sb, 'show_name', lambda self: self.name+'uu') # 為對象增加動態方法44print(sb.show_name(sb))45 # 結果:張飛uu46 47 # delattr刪除屬性 有就刪除沒有就報錯4849 delattr(sb, 'ak117') # 刪除 對象sb的ak117屬性50print(sb.__dict__)51 # 結果{'name': '張飛', 'pwd': 38, 'sb': 27, 'show_name': <function <lambda> at 0x002DC660>}52 # delattr(sb, 'rrr') # 如果不存在此屬性將會報錯53 # print(sb.__dict__)四方法演示
類也是對象
classFoo:name = '38'deffunc():return'AK117' @staticmethoddeffunct():return'funct'print(getattr(Foo, 'name'))print(getattr(Foo, 'func')())print(Foo, 'funct')
反射當前模塊成員
import sysdef s1():print('s1')defs2(): print('s2')this_module = sys.modules[__name__]print(hasattr(this_module, 's1'))print(getattr(this_module, 's2'))
__str__和__repr__
# 改變對象的字符串顯示__str__,__repr__
# 自定製格式化字符串__format__
__str__ 使用方法及含義
# __str__ 使用方法及含義classHuman:def __init__(self, name):self.name = name # 2試驗 def __str__(self): # return'我是str方法,列印對象時調用的就是我,我是存在於object類中' # 1試驗return'my name is %s' % self.name # 2試驗 解釋 %s相當於str() 實際上走的是__str__方法# a = Human() # 1試驗# print(a) # 1試驗# 結果:我是str方法,列印對象時調用的就是我,我是存在於object類中 # 1試驗a = Human('明明') # 2試驗print(a) # 2試驗# 結果 my name is 明明 # 2試驗
__repr__使用方法及含義
# __repr__使用方法及含義class Hunman:def __init__(self, name, age):self.name = nameself.age = age def __repr__(self):return str(self.__dict__)a = Hunman('Mr.He','Twenty-two')print(repr(a)) # 同理repr函數也是調用內置方法 __repr__print('>>>%r'% a) # %r 相當於 repr() 或者 __repr__# 結果# {'name': 'Mr.He', 'age': 'Twenty-two'}# >>>{'name': 'Mr.He', 'age': 'Twenty-two'}# 如果不使用__repr__方法,則返回內存地址
__str__ and __repr__關係
# __str__ and __repr__ relationshipclass Human:def __repr__(self):return str(12345)a = Human()print('%s' % a)# 結果:12345# 原本%s 相當於 __str__方法,但類中無此方法,正常情況下是該報錯的。# 但可以正常輸出結果》結論:__repr__是__str__的備胎。# 如果類中無__str__便去查看父類是否含有,一個父類一個父類找上去直到找到object類中。# 如果沒有便找__repr__代替
__len__
# __len__方法class A:def __init__(self): self.a = 1 self.b = 2 # def __len__(self): # returnlen(self.__dict__)s = A()print(len(s)) # 直接調用了類中的__len__方法# 注意 有些方法在object類中是沒有被收錄的。# 故如果不構建__len__方法,來讀取一個int類型的數據的長度便會報錯# 錯誤類型為:TypeError: object of type'A' has no len()
__del__(析構函數)
析構方法,當對象在內存中被釋放時,自動觸發執行。
註:此方法一般無須定義,因為Python是一門高級語言,程式設計師在使用時無需關心內存的分配和釋放,因為此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的。
# __del__class Currency:def __del__(self):print('執行了我,刪除了你要刪除的數據')a = Currency()del a # 即執行了這個方法,又刪除了變量
__call__
# __call__class Human:def __init__(self, name):self.name = name def __call__(self, *args, **kwargs):'''此處可以寫一些小方法''' print('abc')a = Human('Mr.he')a()# 結果:abc
#python#