class MyClass: pass instance = MyClass() print(type(instance)) print(type(MyClass))輸出結果為:
<class '__main__.MyClass'>
<class 'type'>
class MyClass: data = 1Python 底層執行的是下面這段程式碼:
class = type(classname, superclasses, attributedict)其中等號右邊的 type(classname, superclasses, attributedict) 就是 type 的 __call__ 運算子過載,它會進一步呼叫下面這 2 個函數:
type.__new__(typeclass, classname, superclasses, attributedict) type.__init__(class, classname, superclasses, attributedict)以上整個過程,可以通過如下程式碼進行論證:
class MyClass: data = 1 instance = MyClass() print(MyClass,instance) print(instance.data) MyClass = type('MyClass', (), {'data': 1}) instance = MyClass() print(MyClass,instance) print(instance.data)執行結果為:
<class '__main__.MyClass'> <__main__.MyClass object at 0x000001CB469F7400>
1
<class '__main__.MyClass'> <__main__.MyClass object at 0x000001CB46A50828>
1
class = type(classname, superclasses, attributedict) # 變為了 class = MyMeta(classname, superclasses, attributedict)
建議初學者不要輕易嘗試使用 mateclass。