another easy (im sure) newbie question

Steve Holden sholden at bellatlantic.net
Wed Mar 1 09:49:33 EST 2000


> Shaun Hogan wrote:
> 
> ok i started learning python a week ago.
> ive followed Guido's tutorial and another one, i have a good grasp of
> everthing up to Classes, now the example in the tutorial 9.3.2:
> 
>                         class MyClass:
>                                  "A simple example class"
>                                  i = 12345
>                                  def f(x):
>                                      return 'hello world'
> is where i am at.

You seem to be doing very well!

> the tutorial says "MyClass.i and MyClass.f are valid attribute references,
> returning an integer and a function object,"

Correct.  Both i and f, being defined (by assignment in the case of i, by
definition in the case of f) within the namespace associated with the
class definition, refer to attributes of the class.  As opposed to attributes
of an instance of the class.  No matter how many instances you create (and
you haven't created any yet) MyClass.i and MyClass.f always refer to the
same attributes.

> MyClass.i returns "12345" fine...but MyClass.f gives me "<unbound method
> MyClass.f>"

Seems sensible.  An unbound method is one which is called via the class
definition rather than via an instance of the class.  Since you are just
asking about MyClass.f rather than calling it, you get told what it is.

> how do i get it to return "hello world" or whatever its supposed to do?
> 
Well, calling it would be a good start <0.2 wink>!  Seriously, though,
there are special rules for calling methods of classes...

> also what does the error message "TypeError: unbound method must be called
> with class instance 1st argument" mean???
> 
That's the special part.

Every method call requires an instance of the class as its first argument.
In the case of *bound* methods (called via a reference to an
instance) Python automagically inserts the required first argument.  For
unbound methods you have to do this yourself, explicitly.

So let's create an instance and see what Python tells us about that:

>>> mc = MyClass()
>>> mc.f
<method MyClass.f of MyClass instance at 87b390>

Note, this is no longer an unbound method.  Now let's call it:

>>> mc.f()
'hello world'

Yippee!  Finally, just to prove no sleight-of-hand is involved, let's call
the unbound method and explicity provide the instance it needs:

>>> MyClass.f(mc)
'hello world'


> simple answers im sure, but its got me stuck.

Simple, but subtle.  You are lerning about the underpinning of much of Python's
expressive power.  It's worth taking the time to get it right, as you seem to
be doing.

Good luck!

> any help would be great
> thanks
> Shaun
> 
regards
 Steve
--
"If computing ever stops being fun, I'll stop doing it"



More information about the Python-list mailing list