Strange error with unbound method

Steve Holden sholden at holdenweb.com
Mon Apr 16 12:30:01 EDT 2001


"Fernando Rodríguez" <spamers at must.die> wrote ...
> Hi!
>
> I have a class called ParaStyle (see code below). This class has a
> method called makeBlackAndWhite that returns a new instance of class
> ParaStyle.
>
 ...When activated as a callable using ParaStyle(), rather than being used
as an object reference as in ParaStyle ...

> I want to transform a list of ParaStyle instances into a list of the
> result of applying the makeBlackAndWhite method of each instance.
>
> If I do:
> paraStyles = map( ParaStyle.makeBlackAndWhite, paraStyles )
>
> I get the following error:
> TypeError: unbound method must be called with class instance 1st argument
>
That's because the map() call is the (approximate) equivalent on

result = []
for p in paraStyles:
    result.append(ParaStyle.makeBlackAndWhite(p))
paraStyles = result

In other words, the method doesn't know which instance it is supposed to be
applied to because it's called as an *object method* and therefore note
bound to any particular instance.

> While if I do it with a for loop:
> l = []
> for para in paraStyles:
>     l.append( para.makeBlackAndWhite() )
>
> I dont get any error!  =:-O
>
In this case, of course, you are implicitly providing an instance because
makeBlackAndWhite is here called as an *instance mthod*, and so the instance
is provided as a first argument to the call.

> What's going on???? O:-)
>
The Python interpreter is doing its job! I'm sure other readers will be
happy to supply you with a suitable map()-based implementation. I personally
prefer the explicit solution you give as your second case.

regards
 stEve


[ code snipped ]






More information about the Python-list mailing list