[Tutor] Superclass call problem

Steven D'Aprano steve at pearwood.info
Sun Feb 21 01:19:32 CET 2010


On Sun, 21 Feb 2010 04:50:49 am Alan Harris-Reid wrote:
> Hi,
>
> I am having trouble understanding how superclass calls work.  Here's
> some code...

What version of Python are you using?

In Python 2.x, you MUST inherit from object to use super, and you MUST 
explicitly pass the class and self:

class ParentClass(object):
    def __init__(self, a, b, c):
        do something here

class ChildClass(ParentClass):
    def __init__(self, a, b, c):
        super(ChildClass, self).__init__(a, b, c)

In Python 3.x, all classes inherit from object and you no longer need to 
explicitly say so, and super becomes a bit smarter about where it is 
called from:

# Python 3 only
class ParentClass:
    def __init__(self, a, b, c):
        do something here

class ChildClass(ParentClass):
    def __init__(self, a, b, c):
        super().__init__(a, b, c)


I assume you are using Python 3.0 or 3.1. (If you're 3.0, you should 
upgrade to 3.1: 3.0 is s-l-o-w and no longer supported.)


Your mistake was to pass self as an explicit argument to __init__. This 
is not needed, because Python methods automatically get passed self:

>     def __init__(self):
>         super().__init__(self)

That has the effect of passing self *twice*, when __init__ expects to 
get self *once*, hence the error message you see:

> When the super().__init__ line runs I get the error "__init__() takes
> exactly 1 positional argument (2 given)"





-- 
Steven D'Aprano


More information about the Tutor mailing list