標籤:sign int 操作 形式 val get cep 字元 面向
一、什麼是反射
反射的概念是由Smith在1982年首次提出的,主要是指程式可以訪問,檢測和修改它本省狀態或行為的一種能力(自省)。這一概念的提出很快引發了電腦科學領域關於應用反射性的研究。它首先被程式語言的設計領域所採用,並在Lisp和物件導向方面取得了成績。
python物件導向中的反射:通過字串的形式操作對象相關的屬性。Pythonn中的一切事物都是對象(都可以使用反射)
反射四種方法
一切皆對象,類本身也是一個對象
hasattr
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('john',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__)
Python之物件導向-反射