In this lesson, we will study about the usage of Python self. It is often a point of debate among experts and a topic of confusion for beginners. Let’s try to come clean for everyone.
Table of Contents
Copyclass Person: def static_method(): print("This is a static method")
Now, to make a method which can operate on a real ‘Person’ object we need to provide it with a reference to the object. So, instead of passing the complete object of Person to its own class, we can use the
Copyclass Person: def object_method(self): print("I can do something with self.")
Next, let us look at how it can be used to access fields in the class constructor itself.
Python class self constructor
self can also be used to refer to a variable field within the class:
Copyclass Person: # name made in constructor def __init__(self, n): self.name = n def get_person_name(self): return self.name
In above snippet,
self refers to the name variable of the entire
Person class. Note that if we have a variable within a method, self will not work. That variable is simply existent only while that method is running and hence, is local to that method. For defining global fields (the variables of the complete class), we need to define them OUTSIDE the class methods. Refer python variable scope.
Is self a keyword?
self is used in so many places in Python that people think it’s a keyword. But unlike
this in C++,
self is not a keyword.
We can actually use any name for the first parameter of a method, but it is strongly advised to stick to the convention of calling it
This means that the last class can be made as:
Copyclass Person: #name made in constructor def __init__(another, n): another.name = n; def get_person_name(another): return another.name
See how I used
another this time? It works exactly the same way as
Should we pass self to a method?
Above explanation opens a new question, should we just pass
self to a method? Let’s consider the class Person which contains a method
something defined as:
Copydef something(another, arg1, arg2): pass
personMe is an instance of the class and
personMe.something(arg1, arg2) is called, python internally converts it for us as:
CopyPerson.something(personMe, arg1, arg2)
self variable refers to the object itself.
That’s all for python self and it’s usage in constructor and functions to get the current object reference.
For more Python posts, read here.