python之-- 反射

來源:互聯網
上載者:User

標籤:地址   dog   alt   delattr   python   --   字串   style   isp   

反射定義:通過字串映射或者修改程式運行時的狀態,屬性,方法。
方法有如下4個:
1:getattr(object,name,default=None):根據字串去擷取obj對象裡的對應的方法的記憶體位址,如果是屬性則會直接傳回值。
2:hasattr(object,name):判斷對象object裡是否存在name字串的方法映射
3:setattr(x,y,v) ==》 x.y = v :通過字串設定新的屬性(可以重設普通屬性值,也可以將函數設定為類方法)
4:delattr(x,y)
舉例:
 1 # 將這個方法動態裝入類中進行調用 2 def bulk(self): 3     print(‘%s is yelling...‘ % self.name) 4  5 class Dog(object): 6     def __init__(self,name): 7         self.name = name 8     def eat(self,food): 9         print(‘%s is eat %s‘ % (self.name,food))10 11 obj = Dog(‘沙皮‘)12 mess = input(‘請輸入操作的方法:‘)13 if hasattr(obj,mess):14     #-----刪除---15     #delattr(obj,mess) # 類比傳入name,刪除name屬性16     #print(obj.name)  # 報錯提示沒有name屬性17     #-----以字串列印方法值---18     # fun = getattr(obj,mess) # 這裡將通過getattr得到talk方法的記憶體位址19     # fun(‘baba‘)20     #-----重設屬性值---21     # setattr(obj,mess,‘22‘)  # 這裡可以重新修改已存在的屬性值22     # print(getattr(obj,mess))23 else:24 25     #------設定將類外面的函數引入類中----26     # setattr(obj,mess,bulk) # 動態將bulk函數裝入類中27     # getattr(obj,mess)(obj) # 動態使用getattr方法擷取輸入值,然後將obj對象本身當參數傳入,因為上面的bulk函數有self參數。28 29     # -----設定動態傳入屬性30     setattr(obj,mess,22) # 設定預設屬性值,31     print(getattr(obj,mess))  # 返回預設屬性值2232     # 可以重新設定已存在的屬性值
View Code

 

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.