[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

相关文章

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

MySQL深分页进行性能优化的常见方法

《MySQL深分页进行性能优化的常见方法》在Web应用中,分页查询是数据库操作中的常见需求,然而,在面对大型数据集时,深分页(deeppagination)却成为了性能优化的一个挑战,在本文中,我们将... 目录引言:深分页,真的只是“翻页慢”那么简单吗?一、背景介绍二、深分页的性能问题三、业务场景分析四、

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核