Python ————反射機制

來源:互聯網
上載者:User

標籤:賦值   全域   反射機制   end   time   after   turn   size   根據   

python中的反射功能是由以下四個內建函數提供:hasattr、getattr、setattr、delattr,改四個函數分別用於對對象內部執行:檢查是否含有某成員、擷取成員、設定成員、刪除成員。

# commons.py 檔案 name = "nick" def f1():    return "This is f1." def f2():    return "This is f2." def nb():    return "This is niubily."   # index.py 檔案import commons #根據字串的形式去某個模組中尋找東西target_func = getattr(commons,"f1")     # 找函數result = target_func()print(result) target_func = getattr(commons,"name")   # 找全域變數print(target_func) target_func = getattr(commons,"age",None)   # 找不到返回Noneprint(target_func) #根據字串的形式去某個模組中判斷東西是否存在tarhas_func = hasattr(commons,"f5")     # 找函數print("before:",tarhas_func) # tarhas_func = hasattr(commons,"name") # 找全域變數# print(tarhas_func) #根據字串的形式去某個模組中設定東西setattr(commons,"f5","lambda x: return \"This is new func.\"")  # 設定一個函數setattr(commons,"age",18)       # 設定全域變數 tarhas_func = hasattr(commons,"f5")     # 檢查函數是否存在print("after:",tarhas_func) #根據字串的形式去某個模組中刪除東西delattr(commons,"f5")       # 刪除一個函數 tarhas_func = hasattr(commons,"f5")     # 檢查函數是否存在print("end:",tarhas_func)

對象執行個體

class Foo:   def __init__(self,name,age):       self.name=name       self.age=age   def show(self):        print("擷取到了該函數方法")obj=Foo(‘2018世界盃‘,2018) #hasattr 是否存在欄位print(hasattr(obj,‘name‘))#getattr擷取資訊getname=getattr(obj,‘name‘)print(getname)#setattr賦值setattr(obj,‘time‘,‘2018-6-16‘)print(obj.time)#delattr刪除delattr(obj,‘name‘)print(obj.name)#刪除後報錯AttributeError: ‘Foo‘ object has no attribute ‘name‘

 

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.