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

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):
    pass

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

    def speak(self):
        print(self._name, self._age)

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

class Person(object):
    pass


ClassName = 'Child'
def __init__(self, name, age):
    if age > 20:
        raise ValueError("Child's age must small than 20")
    self._name = name
    self._age = age

def 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):  # 这个是元类
    pass

class ClassTwo(metaclass=type):  # 不是元类,是用元类创建的类
    pass

class ClassThree(object, metaclass=type):   # 与ClassTwo一模一样。不是元类,是用元类创建的类
    pass

class ClassFour(ClassOne):  # 继承自元类,是元类
    pass

print(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_1
    return 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_1
    return 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_2

print('<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')

    @classmethod
    def __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 collections

class MetaAleph(type):
    @classmethod
    def __prepare__(mcs, name, bases):  # 必须要是类方法
        return collections.OrderedDict()

8. 元类的妙用

待续/…

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值