Newbie question on self in classes

Peter Otten __peter__ at web.de
Sat Jan 10 16:56:39 EST 2004


Klaus Oberpichler wrote:

> Hello Python community,
> 
> my simple question is: When is the self reference to a class valid?
> During playing around with python I got the following error message:
> 
>>>> class Test:
> ...  value = 1000
> ...  self.value = 2
> ...
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 3, in Test
> NameError: name 'self' is not defined
> 
> When I do it a different way no error occurs:
> 
>>>> class Test:
> ...  value = 1000
> ...  def f(self):
> ...   self.value = 2
> ...
>>>>
> 
> When is the reference to its own class is generated and valid? What is the
> reason bihind that behaviour?

The name "self" is just a convention. Python passes the instance to a
method, i. e. a def ... inside the class as its first parameter:

>>> class Test:
...     def method(self):
...             self.value = 2
...

So you could say that self is accessible inside (normal) methods.
Now let's create an instance:

>>> t = Test()

Calling the method:

>>> t.method()

This is just a shortcut for:

>>> Test.method(t)

with the important difference that the first form will automatically pick
the "right" method when inheritance comes into play.

Now to the value attribute. The way you defined it, it is a class attribute,
something that ist best avoided at this early state of the learning curve.
What you want is rather an instance attribute, i. e. something that may be
different for every instance of the class. These are initialized in the
__init__() method, which is called implicitly when you say Test():

>>> class Test:
...     def __init__(self):
...             self.value = 1000
...     def method(self, newvalue):
...             self.value = newvalue
...
>>> t = Test()
>>> t.value
1000
>>> t.method(1234)
>>> t.value
1234

>>> Test.method(t, 3210)
>>> t.value
3210

Peter






More information about the Python-list mailing list