Python學習系列之反射

來源:互聯網
上載者:User

標籤:false   com   學習   stdin   tee   nbsp   color   函數   import   

反射的定義

根據字串的形式去某個對象中操作成員

  1. 根據字串的形式去某個對象中尋找成員
  2. 根據字串的形式去某個對象中設定成員
  3. 根據字串的形式去某個對象中刪除成員
  4. 根據字串的形式去某個對象中判斷成員是否存在
反射相關函數

getattr(object,name,[default])

根據字串的形式去某個對象中尋找成員

自訂一個模組(用來測試尋找這個模組裡的某個成員)

# 自訂模組的內容[[email protected] ~]# cat commons.py #!/usr/bin/env pythonBlog_Url = "www.cnblogs.com/zhaijunming5"def f1():    return "F1"def f2():    return "F2"

在commons模組裡尋找某個成員

>>> import commons
>>> getattr(commons, "f1")<function f1 at 0x7fbce5774598> #表示找個這個成員了>>> getattr(commons, "f1f1f1")Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: module ‘commons‘ has no attribute ‘f1f1f1‘ #表示沒找到這個成員,報錯了

執行擷取到的成員(函數)

>>> target_func = getattr(commons, "f1")>>> target_func<function f1 at 0x7fbce5774598>>>> target_func() ‘F1‘

通過設定預設值可以避免擷取不到方法時報錯

# 設定一個預設值為None>>> target_func = getattr(commons, "f1f1f1", None)>>> target_func>>>

通過getattr擷取模組中的全域變數

>>> import commons>>> getattr(commons, "Blog_Url", None)www.cnblogs.com/zhaijunming5

setattr(object,name,value)

根據字串的形式去某個對象中設定成員

設定全域變數

# 擷取commons內的Name變數>>> getattr(commons, "Name", None)# 在commons模組中設定一個全域變數Name,值為Ansheng>>> setattr(commons, "Name", "ZhaiJunMing")# 擷取commons內的Name變數>>> getattr(commons, "Name", None)‘ZhaiJunMing‘

delattr(object,name)

根據字串的形式去某個對象中刪除成員

>>> getattr(commons, "Name")‘ZhaiJunMing‘>>> delattr(commons, "Name")# 擷取不到就報錯>>> getattr(commons, "Name")Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: module ‘commons‘ has no attribute ‘Name‘

hasattr(object,name)

根據字串的形式去某個對象中判斷成員是否存在

# 如果不存在就返回False>>> hasattr(commons, "Name")False>>> setattr(commons, "Name", "ZhaiJunMing")# 如果存在就返回True>>> hasattr(commons, "Name")True

 

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.