isinstance(obj,cls)檢查是否obj是不是類 cls 的對象python
class Foo(object): pass obj = Foo() isinstance(obj, Foo)
實例:函數
class Base(object): pass class Foo(Base): pass obj1 = Foo() print(isinstance(obj1,Foo)) # 檢查第一個參數(對象)是不是第二個參數(類及父類)的實例。 print(isinstance(obj1,Base)) # 檢查第一個參數(對象)是不是第二個參數(類及父類)的實例。 obj2 = Base() print(isinstance(obj2,Foo)) # 檢查第一個參數(對象)是不是第二個參數(類及父類)的實例。 print(isinstance(obj2,Base)) # 檢查第一個參數(對象)是不是第二個參數(類及父類)的實例。
issubclass(sub, super)檢查sub類是不是 super 類的派生類 ui
class Foo(object): pass class Bar(Foo): pass issubclass(Bar, Foo)
實例:this
class Base(object): pass class Foo(Base): pass class Bar(Foo): pass print(issubclass(Bar,Base)) # 檢查第一個參數是不是第二個參數的 子子孫孫類
獲取當前對象是由哪一個類建立。spa
class Foo(object): pass obj = Foo() print(obj,type(obj)) # 獲取當前對象是由那個類建立。 if type(obj) == Foo: print('obj是Foo類型')
實例:設計
class Foo(object): pass class Bar(object): pass def func(*args): foo_counter =0 bar_counter =0 for item in args: if type(item) == Foo: foo_counter += 1 elif type(item) == Bar: bar_counter += 1 return foo_counter,bar_counter # result = func(Foo(),Bar(),Foo()) # print(result) v1,v2 = func(Foo(),Bar(),Foo()) print(v1,v2)
反射的概念是由Smith在1982年首次提出的,主要是指程序能夠訪問、檢測和修改它自己狀態或行爲的一種能力(自省)。這一律唸的提出很快引起了計算機科學領域關於應用反射性的研究。它首先被程序語言的設計領域所採用,並在Lisp和麪向對象方面取得了成績。 rest
python面向對象中的反射:經過字符串的形式操做對象相關的屬性。python中的一切事物都是對象(均可以使用反射)。code
四個能夠實現自省的函數:對象
hasattr:blog
def hasattr(*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:
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'' """ pass
delattr:
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'' """ pass
四個方法的使用例子:
class Foo: f = '類的靜態變量' def __init__(self,name,age): self.name=name self.age=age def say_hi(self): print('hi,%s'%self.name) obj=Foo('egon',73) #檢測是否含有某屬性 print(hasattr(obj,'name')) print(hasattr(obj,'say_hi')) #獲取屬性 n=getattr(obj,'name') print(n) func=getattr(obj,'say_hi') func() print(getattr(obj,'aaaaaaaa','不存在啊')) #報錯 #設置屬性 setattr(obj,'sb',True) setattr(obj,'show_name',lambda self:self.name+'sb') print(obj.__dict__) print(obj.show_name(obj)) #刪除屬性 delattr(obj,'age') delattr(obj,'show_name') delattr(obj,'show_name111')#不存在,則報錯 print(obj.__dict__)
這四個方法適用於類和對象(一切皆對象,類自己也是一個對象)
類也是對象:
class Foo(object): staticField = "old boy" def __init__(self): self.name = 'wupeiqi' def func(self): return 'func' @staticmethod def bar(): return 'bar' print getattr(Foo, 'staticField') print getattr(Foo, 'func') print getattr(Foo, 'bar')
反射當前模塊成員:
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys def s1(): print 's1' def s2(): print 's2' this_module = sys.modules[__name__] hasattr(this_module, 's1') getattr(this_module, 's2')
導入其餘模塊,利用反射查找該模塊是否存在某個方法。
module_test.py:
# -*- coding:utf-8 -*- def test(): print('from the test')
index.py:
# -*- coding:utf-8 -*- """ 程序目錄: module_test.py index.py """ import module_test as obj #obj.test() print(hasattr(obj,'test')) getattr(obj,'test')()