python中的元类_Python中的元类

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

元类的用例可以很多,例如

  1. Logging and profiling

    记录和分析

  2. Dynamically adding new methods

    动态添加新方法

  3. Dynamic resource locking/synchronization

    动态资源锁定/同步

  4. 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中的元类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值