[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

相关文章

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结