[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如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

判断PyTorch是GPU版还是CPU版的方法小结

《判断PyTorch是GPU版还是CPU版的方法小结》PyTorch作为当前最流行的深度学习框架之一,支持在CPU和GPU(NVIDIACUDA)上运行,所以对于深度学习开发者来说,正确识别PyTor... 目录前言为什么需要区分GPU和CPU版本?性能差异硬件要求如何检查PyTorch版本?方法1:使用命

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息