self
is usually one of the hardest things for beginners to grasp. It is one of those concepts that you probably need to google about several times before you start to get any idea + you have to try it out and use it to fully understand it.
But contrary to its reputation self
is really a simple thing. It just represents an instance of a class.
Let’s take a look at a simple example:
class User:
# We define three input arguments to the method
# self - used to represent the instance itself
# name, and email used to define the nature of
# the object.
def __init__(self, name, email):
# self is used to bind instance attributes
# (e.g. self.name) to input arguments (i.e. name)
self.name = name
self.email = email
def greet(self):
# since self refers to an instance of this class
# it is used to obtain it's own attribute (remember
# that attributes of a class can be variables or
# methods)
# https://docs.python.org/3.8/tutorial/classes.html#instance-objects
print(f'Welcome {self.name}')
if __name__ == '__main__':
john = User('John', 'john@example.com')
john.greet()
Each method in a class (except class methods, and static methods) has to accept at least one argument - self
, and it has to be listed as the first positional argument. The value for the self
is supplied to the method at runtime by the interpreter.
Since self
is a representation of instance of a class, this means that any attribute we assign to an instance is bound to that specific instance:
john = User('John', 'john@example.com')
jane = User('Jane', 'jane@example.com')
john.name # will print 'John' because self.name = 'John'
# and now the value 'John' is bound to the john instance
jane.name # will print 'Jane' because self.name = 'Jane'
# and now the value 'Jane' is bound to the jane instance
Let’s do a sanity check. The built-in id()
function shows the address of an object in memory. We’ll make a method which prints the ID of self
and then we’ll also use the method on the instance of that class:
class Test:
def show_id(self):
print(id(self))
# Make an instance
t1 = Test()
# Print id of 'self'
t1.show_id() # -> 139758305086992
# Print id of the instance
print(id(t1)) # -> 139758305086992
That’s right, you’ll get same values for IDs, because these are identical objects.
self
is also a convention (not a Python keyword). You can name it whatever you want, though this is not advisable. Sometimes it’s better to stick to conventional wisdom.