Second parameter of super()?

后端 未结 2 2086
灰色年华
灰色年华 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:17

    The only thing that causes all these ambiguities is that "why obj = super(B).__init__() works?". That's because super(B).__self_class__ returns None and in that case you're calling the None objects' __init__ like following which returns None:

    In [40]: None.__init__()
    

    Regarding the rest of the cases, you can simply check the difference by calling the super's essential attributes in both cases:

    In [36]: class B(A):                                                                     
            def __init__(self):                                                         
                    obj = super(B, self)
                    print(obj.__class__)
                    print(obj.__thisclass__)
                    print(obj.__self_class__)
                    print(obj.__self__)
       ....:         
    
    In [37]: b = B()
    
    
    
    <__main__.B object at 0x7f15a813f940>
    
    In [38]: 
    
    In [38]: class B(A):                                                                     
            def __init__(self):                                                         
                    obj = super(B)
                    print(obj.__class__)
                    print(obj.__thisclass__)
                    print(obj.__self_class__)
                    print(obj.__self__)
       ....:         
    
    In [39]: b = B()
    
    
    None
    None
    

    For the rest of the things I recommend you to read the documentation thoroughly. https://docs.python.org/3/library/functions.html#super and this article by Raymond Hettinger https://rhettinger.wordpress.com/2011/05/26/super-considered-super/.

    Moreover, If you want to know why super(B) doesn't work outside of the class and generally why calling the super() without any argument works inside a class you can read This comprehensive answer by Martijn https://stackoverflow.com/a/19609168/2867928.

    A short description of the solution:

    As mentioned in the comments by @Nathan Vērzemnieks you need to call the initializer once to get the super() object work. The reason is laid behind the magic of new super object that is explained in aforementioned links.

    In [1]: class A:
       ...:     def __init__(self):
       ...:         print("finally!")
       ...:
    
    In [2]: class B(A):
       ...:     def __init__(self):
       ...:         sup = super(B)
       ...:         print("Before: {}".format(sup))
       ...:         sup.__init__()
       ...:         print("After: {}".format(sup))
       ...:         sup.__init__()
       ...:
    
    In [3]: B()
    Before: , NULL>
    After: , >
    finally!
    

提交回复
热议问题