Step1:type函數的定義
type() 函數如果只傳入一個參數則返回該參數對象的類型,如果傳入三個參數則返回新的類型對象。
通常情況下,我們經常使用到 type 的第一種用法,即只傳入一個參數,很少使用到第二種或根本就不知道 type 還有傳入三個參數的用法。今天我們將要重點講一下這個用法。
Step2:示例1
1 class A(object): 2 num=100 3 4 class AA(object): 5 bar=True 6 7 def isShow(self): 8 print(self.bar) 9 10 def info(self): 11 print(self.num) 12 13 @staticmethod 14 def static_info(): 15 print("the static of method") 16 17 @classmethod 18 def class_info(cls): 19 print(cls.num) 20 21 B = type("B",(A,AA,),{"info":info,"static_info":static_info,"class_info":class_info,"isShow":isShow,"param":999}) 22 23 if __name__ == '__main__': 24 b=B() 25 b.info() 26 b.static_info() 27 b.class_info() 28 b.isShow() 29 print(b.param)
Type() 方法參數解釋:
“B” 這個字符串表示當前定義的類名
(A,AA,) 這個元組里面定義的是上面B的父類
{}后面的這個字典表示是方法和屬性 使用見main方法中的操作。
Step3:示例2
1 def upper_params(future_class_name, future_class_parents, future_class_attr): 2 # 遍歷屬性字典,把不是__開頭的屬性名字變為大寫 3 newAttr = {} 4 for name, value in future_class_attr.items(): # 遍歷字典 5 if not name.startswith("__"): # 如果不是以__開頭 6 newAttr[name] = value.upper() 7 #將future_class_attr字典中的鍵大寫,然后賦值 8 return type(future_class_name, future_class_parents, newAttr) # 第三個參數為新修改好的值(類名,父類,字典) 9 10 class Test(object, metaclass=upper_params): 11 # 使用upper_attr對類中值進行修改 12 name = 'tony' # 一開始創建Foo類時 13 print(hasattr(Test, 'name')) # hasattr查看Foo類中是否存在bar屬性 14 print(hasattr(Test, 'NAME')) 15 test = Test() # 實例化對象 16 print(test.name) # 輸出
使用說明:
1.上面的使用其實是引入了元類的概念,那么什么是元類了?
我們知道了 Python 中的類也是對象,元類就是用來創建這些類(對象)的,元類就是類的類。函數 type 實際上是一個元類。type 就是 Python 在背后用來創建所有類的元類。type就是創建類對象的類。
你可以通過檢查 class 屬性來看到這一點。Python中所有的東西,注意,我是指所有的東西——都是對象。這包括整數、字符串、函數以及類。它們全部都是對象,而且它們都是從一個類創建而來。
2.metaclasss有什么用?
type 可以創建類,如果存在一個方法,返回一個 type 動態創建的類,在使用 class 定義類的時候,把這個方法賦值給 metaclass,就可以實現動態的改變 class 的定義。
歡迎關注【無量測試之道】公眾號,回復【領取資源】
Python編程學習資源干貨、
Python+Appium框架APP的UI自動化、
Python+Selenium框架Web的UI自動化、
Python+Unittest框架API自動化、
資源和代碼 免費送啦~
文章下方有公眾號二維碼,可直接微信掃一掃關注即可。
備注:我的個人公眾號已正式開通,致力於測試技術的分享,包含:大數據測試、功能測試,測試開發,API接口自動化、測試運維、UI自動化測試等,微信搜索公眾號:“無量測試之道”,或掃描下方二維碼:
添加關注,讓我們一起共同成長!