Second parameter of super()?

后端 未结 2 2067
灰色年华
灰色年华 2021-02-05 13:32

A colleague of mine wrote code analogous to the following today, asked me to have a look, and it took me a while to spot the mistake:

class A():                          


        
2条回答
  •  时光说笑
    2021-02-05 14:31

    The confusion here comes from the fact that (in a class definition context) super() gives a bound super object which then delegates __init__ to its __self_class__, while super(B) creates an unbound super object which, because its __self_class__ is None, does not delegate.

    In [41]: class Test(int):
        ...:     def __init__(self):
        ...:         print(super().__self_class__)
        ...:         print(super().__init__)
        ...:         print(super(Test).__self_class__)
        ...:         print(super(Test).__init__)
        ...:
    
    In [42]: Test()
    
    
    None
    
    

    So when you call super(B).__init__(), it creates an unbound super but then immediately calls __init__ on it; that, because of the magic described in the various links in this other answer, binds that unbound super. There are no references to it, so it disappears, but that's what's happening under the hood.

提交回复
热议问题