In this section, we will learn about the keyword self in Python.
Note: We are assuming you already familiar with the Python Class and Object in general.
What is self in Python
The `self` keyword is used as the first parameter in class methods and it refers to the object that invokes those methods.
Basically, by default and when just creating a method, the `self` keyword does not refer to anything! But when we create an object from a class and then use that object to call a method, then the object becomes the reference of the `self` method in the target method that is being called.
Now, using the `self` keyword, we can access and call other methods and attributes of the object that is calling a method.
For example, if the target object has an attribute named `firstName` or `lastName` for example, then we can access those attributes using `self.firstName` or `self.lastName` as the keyword `self` refers the target object.
Note that by default, there’s no need to use the `self` keyword when we want to call an attribute or method of a class! We can simply call these values without the need to use the `self` keyword.
But one of the times that this `self` keyword becomes handy is when we use the same name for different purposes! For example, an object has an attribute named `firstName` and also there’s a method that has a local variable with this name! Now, if we want to call the attribute `firstName` in that method, we need to prefix the target attribute with `self` keyword in order to avoid name collision.
Example: Python class self
class Parent: def __init__ (self, firstName, lastName): self.firstName = firstName self.lastName = lastName def setFirstName(self, firstName): self.firstName = firstName
How Does Python self Keyword Work?
Note that the `setFirstName` method has a parameter named `firstName`. Now, within the body of this method, the purpose is to assign the argument of this method to the `firstName` attribute of the object. So here if we don’t use the `self` keyword, the execution engine has no idea which `firstName` points to the object’s attribute and which one is the local parameter of the method!
Using the self keyword as the return value of a Method in Python:
Other than using the `self` keyword as the parameter of a method and using it in the body of methods, this keyword can be used as the returned value of a method as well!
In that case, we’re basically returning a pointer to the object that invoked the method from the target method. (This means the return value is not a copy object! But just a pointer to the same object)
Example: python self keyword
class Parent: def __init__ (self, firstName, lastName): self.firstName = firstName self.lastName = lastName def returnSelf(self): return self parent1 = Parent("John","Doe") parent2 = parent1.returnSelf() parent3 = parent1 parent2.firstName = "Jack" print(parent1.firstName) parent3.firstName = "Omid" print(parent1.firstName)