I find this syntax astoundingly annoying. Every time I rename my class, I have to change this call for no apparent reason. Isn't there some __c开发者_Python百科lass__
magic variable or something I can use at least? Interested in answers for Python 2.5, but it doesn't hurt to know if later versions fixed this.
As far as I know, this isn't possible in 2.5. However, in 3.0, this was changed so that you can simply call super().__init__()
.
This is fixed in Python 3. http://docs.python.org/py3k/library/functions.html#super
http://www.python.org/dev/peps/pep-3135/
If your class only inherits from one class it is safe to do just this:
class B(A):
def __init__(self):
A.__init__(self)
But I could be mistaken.
In Python 3.0, the super() can be called without arguments to do the same thing.
EDIT: As pointed out by Alex, this causes infinite recursion when there is more than a single level of inheritance. Do not use this approach.
Yes, "new" style classes have a __class__
attribute available which can be used, eg.
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 a class were to 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
精彩评论