python中的元類
Python元類 (Python metaclass)
A metaclass is the class of a class. A class defines how an instance of a class i.e.; an object behaves whilst a metaclass defines how a class behaves. A class is an instance of a metaclass.
元類是類的類。 一個類定義了一個類的實例。 一個對象的行為而元類定義了一個類的行為。 類是元類的實例。
A metaclass is most commonly used as a class-factory. While an object is created by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the __init__ and __new__ methods, metaclasses allows implementing 'additional things' when creating a class, like replace the class with something else entirely.
元類最常用作類工廠。 當通過調用類創建對象時,Python通過調用元類創建一個新類(執行“ class”語句時)。 與__init__和__new__方法結合使用,元類允許在創建類時實現“其他東西”,例如用其他東西完全替換該類。
When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the base classes of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases, and attributes of the class to instantiate it.
當執行class語句時,Python首先將class語句的主體作為普通代碼塊執行。 生成的名稱空間(字典)保留了將來類的屬性。 通過查看待定類的基類(繼承了元類 ), 待定類的__metaclass__屬性(如果有)或__metaclass__全局變量來確定元類。 然后使用該類的名稱,基數和屬性調用該元類以實例化它。
The usecases of metaclass can be numerous, like
元類的用例可以很多,例如
Logging and profiling
記錄和分析
Dynamically adding new methods
動態添加新方法
Dynamic resource locking/synchronization
動態資源鎖定/同步
Registering the class at creation
創建時注冊課程
定義元類 (Defining Metaclass)
Metaclass are defined just like any other class, but they inherit from 'type'. The metaclass is automatically invoked when the class statement using metaclass ends. If a metaclass keyword is used on the other hand, the class assigned to it will be invoked instead of 'type',
元類的定義與其他任何類一樣,但是它們從'type'繼承。 當使用元類的類語句結束時, 元類將自動被調用。 另一方面,如果使用metaclass關鍵字 ,則會調用分配給它的類,而不是'type' ,
>>> class MyMeta(type):
... def __new__(cls, clsname, superclasses, attrdict):
... print("class name:{}".format(clsname))
... print("super class name{}".format(superclasses))
... print("attribute dict{}".format(attrdict))
... return type.__new__(cls, clsname, superclasses, attrdict)
...
Use the above class like below,
使用上面的類,如下所示,
>>> class test1:
... pass
...
>>> class test2(test1, metaclass=MyMeta):
... pass
...
Output (Observe that we see that MyMeta__new__ is invoked and not from 'type')
輸出(觀察到我們看到MyMeta__new__被調用,而不是從'type'中調用)
class name:test2
super class name(<class '__main__.test1'>,)
attribute dict{'__module__': '__main__', '__qualname__': 'test2'}
>>>
使用元類創建單例 (Creating Singletons using Metaclass)
The singleton pattern is a design pattern that puts a constraint in the instantiation of a class to only one object. Singleton design pattern is used in cases where exactly one object is required.
單例模式是一種設計模式,它在類的實例化中僅對一個對象施加了約束。 單例設計模式用于僅需要一個對象的情況。
>>> class MySingleton(type):
... _instances = {}
... def __call__(cls, *args, **kwargs):
... if cls not in cls._instances:
... cls._instances[cls] = super(MySingleton,cls).__call__(*args, **kwargs)
... return cls._instances[cls]
>>> class SingletonClass(metaclass= MySingleton):
... pass
...
>>> class RegularClass():
... pass
...
>>> test1 = SingletonClass()
>>> test2 = SingletonClass()
>>>
>>> print(test1 == test2)
True
>>> test1 = RegularClass()
>>> test2 = RegularClass()
>>> print(test1 == test2)
False
翻譯自: https://www.includehelp.com/python/metaclass.aspx
python中的元類