python - 元类,基础构造函数不会被调用

时间:2017-05-19 06:59:20

标签: python

我创建了一个元类,它会覆盖默认的 init 函数,以便添加私有变量。

问题是,如果我自己没有明确地调用它,那么基类的 init 函数就不会被调用。

请看下面的例子

class Base(object):                           
    def __init__(self, x, y):                 
        self._xvar = x                        
        self._yvar = y                        
        print("THIS IS THE CONSTRUCTOR", x, y)


class Derived(Base):                          
    pass 


def main():                   
    derived = Derived(11, 20) 

这将打印

  

这是构造者11 20

即使派生类从不调用

super().__init__(x, y)

这是我的元类:

class MetaTemplateContent(type):
    def __new__(mcs, name, base, dct):
        # This is the original init function
        orig_init = dct.get("__init__")

        # this variable will hold all the functions that has a decorator 
        # If the function name is _content_wrapper it will handle static methods as well
        decorators = []
        for _, value in dct.items():
            if isinstance(value, types.FunctionType):
                if value.__name__ == "_content_wrapper":
                    decorators.append(value)
            elif isinstance(value, staticmethod):
                function = value.__func__
                if function.__name__ == "_content_wrapper":
                    decorators.append(function)

        # This is our wrapper init function which will act as a stub
        def init_wrapper(self, *args, **kwargs):
            if orig_init:
                orig_init(self, *args, **kwargs)

            # This is the local variable I want to add to each instance
            # and fill it with all the functions that has the decorator
            self._callbacks = getattr(self, "_callbacks", [])
            self._callbacks.extend(decorators)

        # replace the original init with our stub
        dct["__init__"] = init_wrapper
        return type.__new__(mcs, name, base, dct)

如果我要将我们的基类重写为:

class Base(object, metaclass=MetaTemplateContent):
    def __init__(self, x, y):                     
        self._xvar = x                            
        self._yvar = y                            
        print("THIS IS THE CONSTRUCTOR", x, y)    


class Derived(Base):                              
    pass


def main():                  
    derived = Derived(11, 20)

不会打印任何内容,因为基本构造函数永远不会被调用。

将super()。 init (x,y)添加到派生的构造函数中但是可以解决这个问题:

class Derived(Base):          
    def __init__(self, x, y): 
        super().__init__(x, y)

但这是多余的,我知道我错过了一些重要的事情。 为什么不调用基类构造函数?

这是python 3.5.3

1 个答案:

答案 0 :(得分:2)

在两种情况下调用基类方法:

  1. 您明确地称之为
  2. 子类未定义(即覆盖)方法
  3. 没有您的元类,情况2适用。如您所知,您的元类为每个使用该元类的类创建__init__。因此,对于您的元类,情境2不再适用,并且不会调用基类构造函数。

    换句话说,如果一个类定义了__init__,它必须在需要时显式调用基类版本。你的元类使得每个类定义__init__,所以如果你想要调用基类__init__,你必须明确地调用它。

    您可以修改您的元类,以便init包装器仅在没有orig_init时才调用超类版本。要做到这一点,init包装器需要访问类,所以你需要交换一些东西,以便在创建类之后在init包装器中进行修补:

    class MetaTemplateContent(type):
        def __new__(mcs, name, base, dct):
            # This is the original init function
            orig_init = dct.get("__init__")
    
            # this variable will hold all the functions that has a decorator 
            # If the function name is _content_wrapper it will handle static methods as well
            decorators = []
            for _, value in dct.items():
                if isinstance(value, types.FunctionType):
                    if value.__name__ == "_content_wrapper":
                        decorators.append(value)
                elif isinstance(value, staticmethod):
                    function = value.__func__
                    if function.__name__ == "_content_wrapper":
                        decorators.append(function)
    
            # make the class first
            cls = type.__new__(mcs, name, base, dct)
    
            # This is our wrapper init function which will act as a stub
            def init_wrapper(self, *args, **kwargs):
                if orig_init:
                    orig_init(self, *args, **kwargs)
                else:
                    super(cls, self).__init__(*args, **kwargs)
    
                # This is the local variable I want to add to each instance
                # and fill it with all the functions that has the decorator
                self._callbacks = getattr(self, "_callbacks", [])
                self._callbacks.extend(decorators)
    
            # replace the original init with our stub
            cls.__init__ = init_wrapper
            return cls