Why we have to use self in Python methods?
In this article we will learn why we have to use self in Python methods, with practical examples of everyday situations.
What’s up programmer, ok? Let’s learn more about Python!
One of the reasons for self is due to Python’s philosophy of being an explicit language and this can be explained in the Python code philosophy
And this is taken very seriously throughout the language, so much so that the Python code guide is indicated in the documentation itself.
The technical side
Python was initially created for functional programming and started to have the Object Oriented paradigm
So when developers were creating these features, they decided that the first argument of each method should be the object of this method.
Conventioning that it would be called self
A hidden argument that works to reference that object in question
Let’s see a practical example:
class Human: def __init__(self, name): self.name = name def showName(self): print("The name is: " + self.name) matheus = Human('Matheus') print(matheus.name) matheus.showName()
So here self helps us both define properties referring to the object and also create methods that use a property of the object.
In this article we learned why we have to use self in Python methods
This was a choice in the language design, to make this argument that references the method object implicit.
Following the Python standard of the language, which is a philosophy divided into characteristics that can define the Python language
Want to learn more about Python? Click here!