Python - why use "self" in a class?
Just as a side note: self
is actually just a randomly chosen word, that everyone uses, but you could also use this
, foo
, or myself
or anything else you want, it's just the first parameter of every non static method for a class. This means that the word self
is not a language construct but just a name:
>>> class A:
... def __init__(s):
... s.bla = 2
...
>>>
>>> a = A()
>>> a.bla
2
A.x
is a class variable.
B
's self.x
is an instance variable.
i.e. A
's x
is shared between instances.
It would be easier to demonstrate the difference with something that can be modified like a list:
#!/usr/bin/env python
class A:
x = []
def add(self):
self.x.append(1)
class B:
def __init__(self):
self.x = []
def add(self):
self.x.append(1)
x = A()
y = A()
x.add()
y.add()
print("A's x:", x.x)
x = B()
y = B()
x.add()
y.add()
print("B's x:", x.x)
Output
A's x: [1, 1]
B's x: [1]