[Tutor] inheritance and super() function in python
Steven D'Aprano
steve at pearwood.info
Tue Apr 22 16:51:46 CEST 2014
On Tue, Apr 22, 2014 at 09:48:51AM -0400, Jorge Leon wrote:
> Good day,
>
>
> I have programmed a base class for an environment I have with no problem,
> but when it comes to referencing the base class's constructor in the
> derived class's constructor I have been getting errors:
What version of Python are you using? With super, that is actually
critical.
> *TypeError: Error when calling the metaclass bases*
> * module.__init__() takes at most 2 arguments (3 given)*
Read the error message. Why is it refering to *module*.__init__?
My guess is that you have a module called Obstacle, and a class called
Obstacle, and you have mixed them up. Maybe you are doing this:
# file Obstacle.py
class Obstacle:
# code goes here
# Another file
import Obstacle
class Cylinder(Obstacle)
I can reproduce your error that way:
py> import math
py> class X(math):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: module.__init__() takes at most 2 arguments (3 given)
You need to say
class Cylinder(Obstacle.Obstacle)
Better still, use the naming convention that modules are in lowercase,
and classes in CamelCase:
import obstacle
class Cylinder(obstacle.Obstacle):
...
Even better still, Python is not Java. There is no need to put every
class in its own file.
> Here's how my base class' constructor looks like (position = [x, y, z]):
> *class Obstacle:*
> * def __init__(self,position):*
> * self.position = position*
In Python 2, that is a "classic class", or old-style class, and super
will not work correctly. You need to inherit from object:
class Obstacle(object)
In Python 3, there is no difference and it should be fine.
--
Steven
More information about the Tutor
mailing list