How to call super (MyClass, self) .__ init __ () without MyClass?

I find this syntax strikingly annoying. Every time I rename my class, I have to change this call for no apparent reason. Isn't there any magic variable __class__ or something that I can use, at least? Interested in Python 2.5 answers, but it doesn't bother me to find out if recent versions fixed this.

+4
source share
5 answers

If your class inherits only class one , then it is safe to do this:

 class B(A): def __init__(self): A.__init__(self) 

But I could be wrong.

+3
source

As far as I know, this is not possible in 2.5. However, in 3.0 this has been changed so that you can just call super().__init__() .

+4
source

In Python 3.0, super () can be called with no arguments to do the same.

+2
source

EDIT: As Alex noted, this leads to infinite recursion when there is more than one level of inheritance. Do not use this approach.

Yes, the β€œnew” style classes have the __class__ attribute, which can be used, for example.

 class B(object): def __init__(self): print "B.__init__():" class D(B): def __init__(self): print "D.__init__():" super(self.__class__, self).__init__() >>> d = D() D.__init__(): B.__init__(): >>> dir(d) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> d.__class__ <class '__main__.D'> 

However, this fails if the class must inherit from D :

 >>> class E(D): ... pass ... >>> E() D.__init__(): D.__init__(): [...] D.__init__(): D.__init__(): Traceback (most recent call last): File "<stdin>", line 4, in __init__ File "<stdin>", line 4, in __init__ [...] File "<stdin>", line 4, in __init__ File "<stdin>", line 4, in __init__ RuntimeError: maximum recursion depth exceeded while calling a Python object 
-1
source

Source: https://habr.com/ru/post/1305404/


All Articles