Skip to main content
 首页 » 编程设计

python之派生类不调用 init

2025年05月04日16jillzhang

我试图理解某个 OAuth2/web2py 集成,但 python 类模型中的一些怪癖让我难以理解。具体来说,我有这个 web2py Controller :

def google(): 
    if 'state' in request.vars and request.vars.state == 'google': 
        session.state = request.vars.state 
    person = Person("google") 
    print person.render() 
    return person.render() 

所以我们在这里使用了 Person 类。实现是这样的:

class Person(Base): 

__init__ 不存在于 Person 类中。 Base 类有一个 __init__ 函数:

class Base(object): 
    def __init__( 
        self, 
        hooks=[], 
        theme="%(name)s/", 
        view="app/generic", 
        meta=None, 
        context=None 
        ): 
        from gluon.storage import Storage 
        self.meta = meta or Storage() 
        self.context = context or Storage() 
        self.context.alerts = [] 
        self.context.content_types = [] 
        self.context.categories = [] 
        self.context.menus = [] 
        self.context.internalpages = [] 
        self.theme = theme 
        self.view = view 
 
        # hooks call 
        self.start() 
        self.build() 
        self.pre_render() 
 
        # aditional hooks 
        if not isinstance(hooks, list): 
            hooks = [hooks] 
 
        for hook in hooks: 
            self.__getattribute__(hook)() 

所以我的问题如下:如果 Person 没有显式调用 Base.__init__,它会被调用吗?

或者,更笼统地说:如果派生类没有__init__函数,是否会调用基类__init__函数?而如果派生类有一个__init__函数但是没有显式调用基类的__init__函数呢?

请您参考如下方法:

如果派生类没有__init__函数,父类__init__将被继承和调用。

如果派生类有一个 __init__不调用父级 __init__ 的函数, parent 的 __init__不会被调用。