__new __,__ init__和元类(和超类)

时间:2018-06-01 03:17:55

标签: python-3.x class inheritance metaprogramming metaclass

我花了一天时间试图理解python类模型的复杂性,弄乱了装饰器,元类和超类。

目前,我正在试图找出某些令牌功能的作用,即(这里的背景故事Metaclasses and when/how functions are called

我已经制作了一个新的模拟模块来运行测试,在这里:

#! /usr/bin/env python3

import sys as system
import os  as operating_system

from functools import partial
from time      import perf_counter as counter

class Meta(type):

    @classmethod
    def __prepare__(instance, name, supers, *list, **map):
        print('{} in meta prepare'.format(name))
        return {}

    def __new__(instance, name, supers, attributes, *list, **map):
        print('{} in meta new'.format(name))
        return instance

    def __init__(self, name, supers, attributes, *list, **map):
            print('{} in meta init'.format(self))

    def __call__(self, *list, **map):
        print('{} in meta call'.format(self))
        return type.__call__(self)
        print('after call')

class Super(object):

    def __new__(instance, *list, **map):
        print('{} in Super new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in Super init'.format(self))

    def __call__(self, *list, **map):
        print('{} in Super call'.format(self))
        return object.__call__(self)

class Other(object):

    def __new__(instance, *list, **map):
        print('{} in Other new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in Other init'.format(self))

    def __call__(self, *list, **map):
        print('{} in Other call'.format(self))
        return object.__call__(self)

class MetaSuper(object, metaclass = Meta):

    def __new__(instance, *list, **map):
        print('{} in MetaSuper new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in MetaSuper init'.format(self))

    def __call__(self, *list, **map):
        print('{} in MetaSuper call'.format(self))
        return object.__call__(self)

class DoubleSuper(Super, MetaSuper):

    def __new__(instance, *list, **map):
        print('{} in DoubleSuper new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in DoubleSuper init'.format(self))
        Super.__init__(self, *list, **map)
        MetaSuper.__init__(self, *list, **map)

    def __call__(self, *list, **map):
        print('{} in DoubleSuper call'.format(self))
        return object.__call__(self)

class SuperThenMeta(Super, metaclass = Meta):

    def __new__(instance, *list, **map):
        print('{} in SuperThenMeta new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in SuperThenMeta init'.format(self))
        Super.__init__(self, *list, **map)

    def __call__(self, *list, **map):
        print('{} in SuperThenMeta call'.format(self))
        return object.__call__(self)

class Triple(Super, Other, metaclass = Meta):

    def __new__(instance, *list, **map):
        print('{} in Triple new'.format(instance))
        return instance

    def __init__(self, *list, **map):
        print('{} in Triple init'.format(self))
        Super.__init__(self, *list, **map)
        Other.__init__(self, *list, **map)

    def __call__(self, *list, **map):
        print('{} in Triple call'.format(self))
        return object.__call__(self)

class Simple(Super):

    def __new__(instance, *list, **map):
        print('{} in Simple new'.format(instance))
        return instance.__init__(instance, *list, **map)

    def __init__(self, *list, **map):
        print('{} in Simple init'.format(self))
        Super.__init__(self, *list, **map)
        Other.__init__(self, *list, **map)

    def __call__(self, *list, **map):
        print('{} in Simple call'.format(self))
        return object.__call__(self)    

def main():
    #thing = SuperThenMeta()
    #other = DoubleSuper()
    last  = Super()
    simp  = Simple()
    trip  = Triple()

if __name__ == '__main__':
    main()

TL; DR,我在这些工作片之间尝试了几种不同的设置。

如果我运行它,这是输出:

MetaSuper in meta prepare
MetaSuper in meta new
SuperThenMeta in meta prepare
SuperThenMeta in meta new
Triple in meta prepare
Triple in meta new
<class '__main__.Super'> in Super new
<class '__main__.Simple'> in Simple new
<class '__main__.Simple'> in Simple init
<class '__main__.Simple'> in Super init
<class '__main__.Simple'> in Other init
Traceback (most recent call last):
File "./metaprogramming.py", line 134, in <module>
  main()
File "./metaprogramming.py", line 131, in main
  trip = Triple()
TypeError: __new__() missing 3 required positional arguments: 'name', 'supers', and 'attributes'

由此,我有几个问题:

  • 我应该在函数末尾调用实例。 init (实例,*列表,**地图)?我不这么认为,但在“简单”示例中添加它似乎有效,而“超级”从未到达 init 。我的印象是通过在我自己的调用方法中调用object。调用,这将由它的默认实现处理,但在整个程序期间没有__call__s。

  • 为什么调用Triple()首先调用元类 new ?如果这是正常的,这是否意味着这是具有元类的任何类的典型?这是与超类类似的行为吗?

  • 我希望调用在此列表中。是否在对象的创建例程中调用它(例如[prepare],new,init)?

我知道这是很多信息,所以感谢你阅读这篇文章;任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:1)

元类'__new__

方法__new__是创建新实例的方法。因此它的第一个参数不是和实例,因为还没有创建它,而是类本身。

对于元类,__new__应该返回元类的实例,即。它的签名是这样的:

class Meta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        ...
  • metacls是元类本身。

  • name是一个表示所在类名称的字符串 实例

  • bases是类将继承的类的元组。

  • namespace是类的名称空间,这是对象 由__prepare__返回,现在填充了类属性。

  • **kwargs是在实例化时传递给类的任何关键字参数

要实例化一个类,您需要调用type.__new__,这是默认的元类。您通常可以致电super().__new__

class Meta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        print('You can do stuff here')

        cls = super().__new__(metacls, name, bases, namespace, **kwargs)

        # You must return the generated class
        return cls

元类'__init__

__init__方法与任何其他类的行为没有区别。如果__new__返回了期望类型的实例,它将接收创建的实例(此处为类)作为参数。在您的示例中,__new__不会返回Meta类型的对象。它返回Meta本身,其类型为type

在实例化中永远不会调用以下__init__方法。

class Meta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        return None # or anything such that type(obj) is not Meta

    def __init__(self, name, bases, namespace, **kwargs):
        # This will never be called because the return type of `__new__` is wrong
        pass

在实例化时调用以下内容,因为Meta.__new__正确返回类型为Meta的对象。

class Meta(type):
        def __new__(metacls, name, bases, namespace, **kwargs):
            return super().__new__(metacls, name, bases, namespace, **kwargs)

        def __init__(self, name, bases, namespace, **kwargs):
            print('__init__ was called')

元类'__call__

同样,__call__的行为与任何其他类别的行为没有什么不同。当您尝试调用元类的实例时调用它,而在调用元类创建时调用__new____init__实例(一个类)。

当然,调用一个类应该返回一个实例,所以不要忘记调用super().__call__并返回其结果,否则你将短路实例创建。

class Meta(type):
    def __call__(self, *args, **kwargs):
        print(f'An instance was called with {args}')
        return super().__call__(self, *args, **kwargs)

# This declaration if what calls __new__ and __init__ of the metaclass
class Klass(metaclass=Meta):
    pass

# This calls the __call__ method of the metaclass
instance = Klass()