How to make super() work by manually filling the __class__ cell?

前端 未结 3 921
挽巷
挽巷 2020-12-29 10:30

In Python 3 one can use super() instead of super(MyClass, self), but this only works in methods that were defined inside the class. As described in

3条回答
  •  抹茶落季
    2020-12-29 10:50

    Maybe, but by would you? In both cases you need to somehow be explicit of which class it is, because the implicit way didn't work. Maybe you can set the cell explicitly somehow, but there is no reason to do that. Just pass in the parameters explicitly.

    def __init__(self):
        print('calling __init__')
        super(self.__class__, self).__init__()
    
    class C(object):
        __init__ = __init__
    
    if __name__ == '__main__':
        c = C()
    

    (It's better if you can pass in the actual class directly, like so:

    def __init__(self):
        print('calling __init__')
        super(C, self).__init__()
    
    class C(object):
        __init__ = __init__
    
    if __name__ == '__main__':
        c = C()
    

    But if you can that, you could put the __init__ on C directly, so assume you can't.

提交回复
热议问题