**python面向物件進階
阿新 • • 發佈:2018-11-03
isinstance(obj,cls)和issubclass(sub,super)
#isinstance(obj,cls)檢查是否obj是否是類 cls 的物件 class Foo(object): pass obj = Foo() isinstance(obj, Foo) #issubclass(sub, super)檢查sub類是否是 super 類的派生類 class Foo(object): pass class Bar(Foo): pass issubclass(Bar, Foo)
反射:程式可以訪問,檢測和修改本身執行狀態或行為的一種能力(自省)
Python中可以實現自省的四個函式(通過字串的形式操作相關屬性)
hasattr getattr setattr delattr
class test: def __init__(self,x,y,z): self.x = x self.y = y self.z = z def func(self): return self.x+self.y+self.z s = test(1,2,3) # hasattr判斷是否含有某屬性 print(hasattr(s,'x')) # getatter獲取屬性v = getattr(s,'func') print(v()) #setattr設定屬性 setattr(s,'w',4) print(s.__dict__) # delattr刪除屬性 delattr(s,'w') print(s.__dict__)