[Tutor] attribute references unbound method

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Mar 6 18:13:17 2003


On Fri, 7 Mar 2003, reavey wrote:

>  >>>class MyClass:
>            "a simple example"
>             n = 1234
>             def f(self):
>                  print "hello"
>
>  >>>MyClass.n
> 1234
>  >>>MyClass.f
> <unbound method MyClass.f>
>  >>>MyClass.f(self)
> NameError: name 'self' is not defined
>
> I found this trying to learn class objects in the Python Tutorial 9.3.2
> I know I'm doing something wrong, but can't put my finger on it.


Hi Mike,

Try:

###
instance = MyClass()
MyClass.f(instance)
###

That is, we first create an instance of a MyClass.  Once we have that,
then we can send it over to MyClass.f() as a parameter.



Let's look back at that error message:

###
>>> MyClass.f(self)
NameError: name 'self' is not defined
###

When Python tries to evaluate something like:

    MyClass.f(self)

Python's first reaction is to figure out what 'self' means.  (Actually,
that's not quite true; Python actually tries to figure out what
'MyClass.f' is, but your experiments above show that it has no problem
seeing that 'MyClass.f' is an "unbound function".)

That NameError error message, then, is just saying that Python has no idea
what 'self' is; it's similar to what happens when we try to use a variable
name that hasn't been assigned:

###
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'foo' is not defined
###

So the error that you were getting isn't really too related to the OOP
stuff that you're experimenting with.


I hope this helps!