Newbie question on self in classes

K

Klaus Oberpichler

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:
.... 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:
.... 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?

Best regards
Klaus
 
P

Peter Otten

Klaus said:
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:

... 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:

... 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:
.... def method(self):
.... self.value = 2
....

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

Calling the method:

This is just a shortcut for:

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():
.... def __init__(self):
.... self.value = 1000
.... def method(self, newvalue):
.... self.value = newvalue
....
3210

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top