0
What exactly does 'self' parameter do in Python?
I tried to understand but can't get my head around it.
2 Answers
+ 8
It it used in defining class methods and operators. When you use it before a variable, you mean the particular object parameter, instead of a class parameter.
Check it out:
class A:
x = 1 # this is a class variable x
# a method to print the class variable x
def show_class():
print(A.x)
def __init__(self, x):
self.x = x
# a method to show the variable x of an object
def show_object(self):
print(self.x)
A1 = A(6)
# this will print out the A class x (a class variable)
A.show_class() # 1
# this will show the x of A1 object of class A
A1.show_object() # 6
By the way, you can use whatever word for that. "self" is just a common convention.
+ 1
Beside what Kuba SiekierzyĹski said, think about this... class are "descriptions" that genarlize use of instance of that class. Now, given a class X, with attributes/methods am1, am2.. amn, EVERY instance of class X will have OWN am1, am2 ... amn then, logically, python must offer a way to access to current instance of class X (for access to OWN attributes/methods)... This is made with the first parameter (usually called self but its not mandatory) that give you the current (in execution context) instance of that class.
Take note that this is NOT true for static methods because they are indipendent from instance (you can considerate they like normal functions that are logically correlate to a class)