[Tutor] inheritance, python and pygame
Steven D'Aprano
steve at pearwood.info
Wed Oct 12 00:41:20 CEST 2011
rail shafigulin wrote:
> i'm trying to learn OOP, python and pygame at the same time. so far it has
> been ok, but i stumbled onto a problem
Hugo has already pointed out that you mispelled __init__, and that in
Python 3 you don't need to explicitly provide arguments to super().
> class BaseSprite(pygame.sprite.Sprite):
> def __init(self, imagefile):
> super(type(self), self).__init__()
Should be written like this in Python 3:
def __init__(self, imagefile):
super().__init__()
However, for those still using Python 2.x, you might be tempted to write
this:
def __init__(self, imagefile):
super(type(self), self).__init__() # NO! Don't do this!
This does not work! But you might be fooled into thinking it does work,
because it *seems* to work if you only check a simple example:
class Base(object):
def __init__(self):
print "Base called"
class Subclass(Base):
def __init__(self):
print "Subclass called"
super(type(self), self).__init__() # Wrong!
It seems to work:
>>> x = Subclass()
Subclass called
Base called
But watch what happens when we subclass again:
class AnotherSubclass(Subclass):
def __init__(self):
print "AnotherSubclass called"
super(type(self), self).__init__()
>>> y = AnotherSubclass()
AnotherSubclass called
Subclass called
Subclass called
Subclass called
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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
The problem is that inside Subclass.__init__ the call to
super(type(self), self) does not necessary give super(Subclass, self).
If the instance being created is from AnotherSubclass, you get
super(AnotherSubclass, self) inside the Subclass.__init__, which then
loops forever.
So in Python 2.x, you must explicitly give the class. You can't use
type(self).
--
Steven
More information about the Tutor
mailing list