Defining class attributes + inheritance

Rhodri James rhodri at wildebst.demon.co.uk
Tue Mar 8 20:53:51 EST 2011


On Wed, 09 Mar 2011 01:00:29 -0000, Martin De Kauwe <mdekauwe at gmail.com>  
wrote:

> class BaseClass(object):
>    def __init__(self, a, b, c, d):
>         self.a = a
>         self.b = b
>         self.c = c
>         self.d = d
>
> class NewClass(BaseClass):
>     def __init__(self):
>         super(NewClass, self).__init__(new)
>         self.new = new
>         print self.new

Two things leap out immediately.  First, BaseClass.__init__ takes four  
parameters besides `self`, but when you call it you only give it one  
parameter, `new`.  It's not going to like that.  Second, where did `new`  
come from?  It's not a parameter to NewClass.__init__, and it doesn't seem  
to be a global.  That's not going to work well either.

However neither of these things are what the traceback is complaining  
about.


>  if __name__ == "__main__":
>
>     A = PreviousClass(1, 2, 3, 4, 5)
>     B = NewClass(1, 2, 3, 4, 5)
>
> $ python test.py
> Traceback (most recent call last):
>   File "model_data.py", line 29, in <module>
>     B = NewClass(1, 2, 3, 4, 5)
> TypeError: __init__() takes exactly 1 argument (6 given)

When you create your NewClass, you give it five parameters (1, 2, 3, 4, 5)  
plus the implicit `self`, which is the "(6 given)" part of the message.   
However NewClass.__init__ takes no parameters aside from `self` (i.e. it  
"takes exactly 1 argument").  There's a mismatch between what you've told  
NewClass.__init__ to expect and what you actually deliver to it.

The point that may be confusing you is that NewClass.__init__ knows  
nothing at all about BaseClass.__init__.  It doesn't inherit parameters  
 from it or anything magical like that; you have to tell it everything.  If  
you want parameters to pass from NewClass.__init__ to BaseClass.__init__  
you will have to provide them somehow.  In this case, I think what you  
meant was something like this:

class NewClass(BaseClass):
     def __init__(self, a, b, c, d, new):
         super(NewClass, self).__init__(a, b, c, d)
	self.new = new
         # etc

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list