self
is not used to declare variables anywhere. self
is the usual name for the first parameter of a method, as the method receives the instance to which it is bound as the first parameter to every call.
It is not used "elsewhere" because it only applies in contexts where there is an instance for a callable to be bound to.
You are probably thinking of something like:
class Foo(object):
y = 1
x = self.y * 2
This is not possible because there is no self
- in fact, at the time that the body of a class statement is evaluated, there is no instance or class object yet in existence. It is also not necessary, because one can simply refer directly to other variables in the scope of the body without using self
.
Note that assignments to members of self, and assignments to variables in class scope do two different things:
class Foo(object):
y = 1 # class variable
def __init__(self):
self.x = self.y * 2 # instance variable, defined by reference to class variable
first = Foo()
Foo.y = 2
first.y = 3
second = Foo()
print first.x # = 2
print second.x # = 4