[Tutor] Need help with using methods in a base class

Alan Gauld alan.gauld at btinternet.com
Sun Sep 7 00:07:21 CEST 2008


"Roy Khristopher Bayot" <roybayot at gmail.com> wrote


> ...     def generateClockPulse(self):
> ...             parallel.Parallel.setSelect(0)
> ...             parallel.Parallel.setSelect(1)
> ...
>>>> a = LightsHandle()
>>>> a.setD(0xF0)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 5, in setD
> TypeError: unbound method setData() must be called with Parallel 
> instance as
> first argument (got int instance instead)

The error merssage gives the clue. Sonce you are calling a method
on a classs not an object you need to pass in the instance reference
explicitly. Its exactly as in calling the base constructor in __init__

class C(P):
   def __init__(self):
      P.__init__(self)    # need to pass self here

> (Some notes: I changed setData() to setD() so that there wont be a
> confusion. Method setData() is from the base class Parallel. 
> Although I
> think setData() could be overriden.)

Thats not necessary, each class creates its owen namespace.

> What have I been doing wrong? Why does it say that I need a Parallel
> instance?

Because the class needs to know where to find the instance variables.
Since you are calling the class directly, not via an instance you have
to pass self explicitly.

Remember that in

class C:
   def m(self, x): print x

c = C(42)


Then c.m() is the same as C.m(c,42). self takes on the value of
the instance in the first case but in the second you have to pass
it directly. When you are inside a methiod you always use the
second form so you always need to pass self.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list