博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中的元类_Python中的元类
阅读量:2548 次
发布时间:2019-05-11

本文共 3622 字,大约阅读时间需要 12 分钟。

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:test2super class name(
,)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

翻译自:

python中的元类

转载地址:http://hyxzd.baihongyu.com/

你可能感兴趣的文章
CSS3 结构性伪类选择器(1)
查看>>
IOS 杂笔-14(被人遗忘的owner)
查看>>
自动测试用工具
查看>>
前端基础之BOM和DOM
查看>>
[T-ARA/筷子兄弟][Little Apple]
查看>>
编译Libgdiplus遇到的问题
查看>>
【NOIP 模拟赛】Evensgn 剪树枝 树形dp
查看>>
java学习笔记④MySql数据库--01/02 database table 数据的增删改
查看>>
两台电脑如何实现共享文件
查看>>
组合模式Composite
查看>>
程序员最想得到的十大证件,你最想得到哪个?
查看>>
我的第一篇CBBLOGS博客
查看>>
【MyBean调试笔记】接口的使用和清理
查看>>
07 js自定义函数
查看>>
jQueru中数据交换格式XML和JSON对比
查看>>
form表单序列化后的数据转json对象
查看>>
[PYTHON]一个简单的单元測试框架
查看>>
iOS开发网络篇—XML数据的解析
查看>>
[BZOJ4303]数列
查看>>
一般处理程序在VS2012中打开问题
查看>>