[Python] 深入理解元类并区分元类中的init、call、new方法

2024-01-25 03:08

本文主要是介绍[Python] 深入理解元类并区分元类中的init、call、new方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[Python] 深入理解元类并区分元类中init、call、new方法

      • 0. 参考书籍和元类的作用总结
      • 1. 元类的定义
      • 2. 区分继承自 type 和使用 metaclass 关键字
      • 3. 类装饰器的运行
      • 4. 元类的运行
      • 5. 理解元类的四个参数
      • 6. 元类中的 init 、call、new 方法
      • 7. 元类中的prepare方法
      • 8. 元类的妙用

0. 参考书籍和元类的作用总结

本文内容参考书籍《流畅的Python》《Effective Python》《编写高质量代码:改善Python程序的91个建议》。我只是知识的搬运工,将知识进行整理,区分出其中的重点并加入自己的理解。感兴趣的最好去翻看原书的相关内容。

  1. 执行到类的代码体结束后时,会调用该类的元类中的__new____init__方法,利用这两个方法,可以对类做一些定制化的操作。
  2. 初始化类的实例时,会调动该类的元类中的__call__方法,利用这个方法,可以对类的实例对象做一下定制化的操作。
  3. 初始化类的实例时,__call____new____init__三个方法的执行顺序是 元类__call__、类的__new__、类的__init__

这三点参考 【6. 元类中的 init 、call、new 方法】,结合代码的执行顺序就可以理解了。

1. 元类的定义

元类是制造类的工厂,元类是用于构建类的类。 这句话很重要!!!这句话很重要!!!这句话很重要!!!

我们正常定义类是这样的:

class Person(object):passclass Child(Person):ClassName = 'Child'def __init__(self, name, age):if age > 20:raise ValueError("Child's age must small than 20")self._name = nameself._age = agedef speak(self):print(self._name, self._age)

我们还可以使用 type 来动态创建类:

class Person(object):passClassName = 'Child'
def __init__(self, name, age):if age > 20:raise ValueError("Child's age must small than 20")self._name = nameself._age = agedef speak(self):print(self._name, self._age)# type 的三个参数分别是 name、bases 和 dict。最后一个参数是一个映射,指定新类的属性名和值。
Child = type('Child', (Person,), {'ClassName': ClassName,'__init__': __init__,'speak': speak})
john = Child('John', 20)
john.speak()
print(Child.__dict__)  # 有 ClassName,__init__ 和 speak 属性

使用 type 关键字去拼接函数和属性来创建类,实在是不够优雅。之所以谈到这个,是为了方便我们后面理解元类是如何动态改变类的属性的。

2. 区分继承自 type 和使用 metaclass 关键字

元类从 type 类继承了构建类的能力。所有类都直接或间接地是 type 的实例,不过只有元类同时也是 type 的子类。搞清楚这句话,意思就是,元类是 type 类的子类。使用 metaclass 关键字的类并不是type 的子类。

class ClassOne(type):  # 这个是元类passclass ClassTwo(metaclass=type):  # 不是元类,是用元类创建的类passclass ClassThree(object, metaclass=type):   # 与ClassTwo一模一样。不是元类,是用元类创建的类passclass ClassFour(ClassOne):  # 继承自元类,是元类passprint(ClassOne.__mro__)
print(ClassTwo.__mro__)
print(ClassThree.__mro__)
print(ClassFour.__mro__)
(<class '__main__.ClassOne'>, <class 'type'>, <class 'object'>)
(<class '__main__.ClassTwo'>, <class 'object'>)
(<class '__main__.ClassThree'>, <class 'object'>)
(<class '__main__.ClassFour'>, <class '__main__.ClassOne'>, <class 'type'>, <class 'object'>)

一定要搞清继承自 type 和使用 metaclass 关键字的不同。前者是元类,后者是由元类创建的类。

3. 类装饰器的运行

为什么要讲类装饰器?因为类装饰器能以较简单的方式做到需要使用元类去做的事情 ——创建类时定制类。

类装饰器与函数装饰器非常类似,是参数为类对象的函数,返回原来的类或修改后的类。我们先来看代码,你可以尝试写一写答案:

"""
请问代码中print语句的打印顺序?
"""
def deco_alpha(cls):print('<[200]> deco_alpha')def inner_1(self):print('<[300]> deco_alpha:inner_1')cls.method_y = inner_1return cls@deco_alpha
class ClassThree():print('<[7]> ClassThree body')def method_y(self):print('<[8]> ClassThree.method_y')if __name__ == '__main__':print('<[12]> ClassThree tests', 30 * '.')three = ClassThree()three.method_y()
<[7]> ClassThree body		# MetaAleph 类的定义体运行了
<[200]> deco_alpha			# 装饰器函数运行了
<[12]> ClassThree tests ......
<[300]> deco_alpha:inner_1	# 装饰器覆盖了原有 MetaAleph 类的 method_y

先运行了被装饰的类 ClassThree 的定义体,然后运行装饰器函数,装饰器函数覆盖了原有 MetaAleph 类的 method_y 方法。

类装饰器有个重大缺点:只对直接依附的类有效。 如果我们新增一个 ClassThree 的子类 ClassFour:

"""
请问代码中print语句的打印顺序?
"""
def deco_alpha(cls):print('<[200]> deco_alpha')def inner_1(self):print('<[300]> deco_alpha:inner_1')cls.method_y = inner_1return cls@deco_alpha
class ClassThree():print('<[7]> ClassThree body')def method_y(self):print('<[8]> ClassThree.method_y')class ClassFour(ClassThree):print('<[9]> ClassFour body')def method_y(self):print('<[10]> ClassFour.method_y')if __name__ == '__main__':print('<[12]> ClassThree tests', 30 * '.')three = ClassThree()three.method_y()print('<[13]> ClassFour tests', 30 * '.')four = ClassFour()four.method_y()
<[7]> ClassThree body
<[200]> deco_alpha
<[9]> ClassFour body
<[12]> ClassThree tests ..............................
<[300]> deco_alpha:inner_1
<[13]> ClassFour tests ..............................
<[10]> ClassFour.method_y

类装饰器可能对子类没有影响。我们把 ClassFour 定义为 ClassThree 的子类,但是发现 ClassFour 的 method_y 方法并没有被覆盖。ClassThree 类上依附的 @deco_alpha 装饰器把 method_y 方法替换掉了,但是这对 ClassFour 类根本没有影响。当然,如果 ClassFour.method_y 方法使用 super(…) 调用 ClassThree.method_y 方法,我们便会看到装饰器起作用,执行 inner_1 函数。

类装饰器的缺点就是一次只定制一个类, 而不是定制整个类层次结构。 而元类就是为了解决这个缺点的,元类可以定制整个类层次结构。

4. 元类的运行

元类可以定制整个类层次结构。我们先看看代码,代码中 print 的语句较多,结构其实并不复杂,尝试写一写答案:

"""
请问代码中print语句的打印顺序?
"""
class MetaAleph(type):print('<[400]> MetaAleph body')def __init__(cls, name, bases, dic):print('<[500]> MetaAleph.__init__')def inner_2(self):print('<[600]> MetaAleph.__init__:inner_2')cls.method_z = inner_2print('<a> ClassFive Before')
class ClassFive(metaclass=MetaAleph):print('<[6]> ClassFive body start')def __init__(self):print('<[7]> ClassFive.__init__')def method_z(self):print('<[8]> ClassFive.method_y')print('<[11]> ClassFive body end')print('<c> ClassSix Before')
class ClassSix(ClassFive):print('<[9]> ClassSix body start')def method_z(self):print('<[10]> ClassSix.method_y')print('<[12]> ClassSix body end')if __name__ == '__main__':print('<[13]> ClassFive tests', 30 * '.')five = ClassFive()five.method_z()print('<[14]> ClassSix tests', 30 * '.')six = ClassSix()six.method_z()
<[400]> MetaAleph body
<a> ClassFive Before
<[6]> ClassFive body start
<[11]> ClassFive body end
<[500]> MetaAleph.__init__
<c> ClassSix Before
<[9]> ClassSix body start
<[12]> ClassSix body end
<[500]> MetaAleph.__init__
<[13]> ClassFive tests ..............................
<[7]> ClassFive.__init__
<[600]> MetaAleph.__init__:inner_2
<[14]> ClassSix tests ..............................
<[7]> ClassFive.__init__
<[600]> MetaAleph.__init__:inner_2

ClassSix 类没有直接引用 MetaAleph 类,但是却受到了影响,因为它是 ClassFive 的子类,进而也是 MetaAleph 类的实例,所以由 MetaAleph.__init__ 方法初始化。 这就是元类的作用了。

5. 理解元类的四个参数

Python 解释器运行到 ClassFive 类的定义体时没有调用 type 构建具体的类定义体,而是调用 MetaAleph 类。看一下示例中定义的 MetaAleph 类,你会发现 __init__ 方法有四个参数。
> cls
这是要初始化的类对象(例如 ClassFive)。
> name、bases、dic
与构建类时传给 type 的参数一样。记得这串代码吗? type 的三个参数 name、bases、dic :
Child = type('Child', (Person,), {'ClassName': ClassName,'__init__': __init__,'speak': speak})

6. 元类中的 init 、call、new 方法

话不多说,直接上代码,体会一下三个方法的运行顺序。

class MetaAleph(type):print('<[100]> MetaAleph body')def __init__(cls, name, bases, dic):super().__init__(name, bases, dic)print('<[500]> MetaAleph.__init__')print('<[501]> MetaAleph. —— name:', name)print('<[502]> MetaAleph. —— bases:', bases)print('<[503]> MetaAleph. —— dic:', dic)     # dic 中包含ClassFive的class_name、__init__、__new__、__call__def __new__(mcs, name, bases, dic):print('<[600]> MetaAleph.__new__')return super().__new__(mcs, name, bases, dic)def __call__(cls, *args, **kwargs):print('<[700]> MetaAleph.__call__')return super().__call__(*args, **kwargs)class ClassFive(metaclass=MetaAleph):print('<[6]> ClassFive body start')class_name = 'ClassFive'def __init__(self):print('<[7]> ClassFive.__init__')def __new__(cls, *args, **kwargs):print('<[8]> ClassFive.__new__')return super().__new__(cls)def __call__(self, *args, **kwargs):print('<[9]> ClassFive.__call__')return '<[10]> ClassFive.__call__ return'if __name__ == '__main__':print('<[13]> ClassFive tests', 30 * '.')five = ClassFive()print(five())  # 为了调用ClassFive.__call__
<[100]> MetaAleph body
<[6]> ClassFive body start
<[600]> MetaAleph.__new__
<[500]> MetaAleph.__init__
<[501]> MetaAleph. —— name: ClassFive
<[502]> MetaAleph. —— bases: ()
<[503]> MetaAleph. —— dic: {'__module__': '__main__', '__qualname__': 'ClassFive', 'class_name': 'ClassFive', '__init__': <function ClassFive.__init__ at 0x0000020FE6CE5B88>, '__new__': <function ClassFive.__new__ at 0x0000020FE6CE5C18>, '__call__': <function ClassFive.__call__ at 0x0000020FE6CE5CA8>, '__classcell__': <cell at 0x0000020FD5D89A38: MetaAleph object at 0x0000020FE658EDC8>}
<[13]> ClassFive tests ..............................
<[700]> MetaAleph.__call__
<[8]> ClassFive.__new__
<[7]> ClassFive.__init__
<[9]> ClassFive.__call__
<[10]> ClassFive.__call__ return

再次总结一下:

  1. 执行到类的代码体结束后时,会调用该类的元类中的__new____init__方法,利用这两个方法,可以对类做一些定制化的操作。一般来说实现 __init__ 方法就可以了。
  2. 初始化类的实例时,会调动该类的元类中的__call__方法,利用这个方法,可以对类的实例对象做一下定制化的操作。
  3. 初始化类的实例时,__call____new____init__三个方法的执行顺序是 元类__call__、类的__new__、类的__init__

7. 元类中的prepare方法

元类构建新类时,__prepare__ 方法返回的映射会传给 __new__ 方法的最后一个参数,然后再传给 __init__ 方法。看示例,十分简单:

其余不变,就增加一个 __prepare__ 方法:

class MetaAleph(type):print('<[100]> MetaAleph body')@classmethoddef __prepare__(mcs, name, bases):  # 必须要是类方法print('<[200]> MetaAleph.__prepare__')_dict = super().__prepare__(name, bases)print('<[201]> MetaAleph.__prepare__ dict:', _dict)return _dict        # 返回的映射会传递给__new__方法的最后一个参数,然后再传给__init__方法... ...
<[100]> MetaAleph body
<[200]> MetaAleph.__prepare__
<[201]> MetaAleph.__prepare__ dict: {}
<[6]> ClassFive body start
<[600]> MetaAleph.__new__
<[500]> MetaAleph.__init__
<[501]> MetaAleph. —— name: ClassFive
<[502]> MetaAleph. —— bases: ()
<[503]> MetaAleph. —— dic: {'__module__': '__main__', '__qualname__': 'ClassFive', 'class_name': 'ClassFive', '__init__': <function ClassFive.__init__ at 0x0000029011AF5CA8>, '__new__': <function ClassFive.__new__ at 0x0000029011AF5D38>, '__call__': <function ClassFive.__call__ at 0x0000029011AF5DC8>, '__classcell__': <cell at 0x00000290027A55E8: MetaAleph object at 0x0000029011466BB8>}
<[13]> ClassFive tests ..............................
<[700]> MetaAleph.__call__
<[8]> ClassFive.__new__
<[7]> ClassFive.__init__
<[9]> ClassFive.__call__
<[10]> ClassFive.__call__ return

使用 collections.OrderedDict() 可以将用户定义的类中声明的字段按顺序记录下来,比如与 CSV 文件中各列的顺序对应起来:

import collectionsclass MetaAleph(type):@classmethoddef __prepare__(mcs, name, bases):  # 必须要是类方法return collections.OrderedDict()

8. 元类的妙用

待续/…

这篇关于[Python] 深入理解元类并区分元类中的init、call、new方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/641900

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以