Python之物件導向-反射

來源:互聯網
上載者:User

標籤: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之物件導向-反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.