This article was long overdue and should have been published before many of the articles in this blog. Better late than never.
self in Python is usually used in an Object Oriented nomenclature, to denote the instance/object created from a Class.
self is the instance itself.
Let’s check the following example:
class MyClass(object): def __init__(self, name): self.name = name print("Initiating the instance!") def hello(self): print(self.name) myclass = MyClass("Dan Inosanto") # Calling the `hello` method via the Instance `myclass` myclass.hello() # Calling the `hello` method vai the class. MyClass.hello(myclass)
The code snippet above is trivial and stupid, but I think it gets the idea across.
We have a class named
MyClass() which takes a
name value as an argument. It also prints the string “Initiating the instance”. The
name value is something that has to be passed while creating an instance.
hello() just prints the
name value that is passed while instantiating the class
We instantiate the class
myclass and pass the string Dan Inosanto as an argument. Read about the great Inosanto here.
Next, we call the
hello() method through the instance. ie..
This should print the name we passed while instantiating
myclass , which should be pretty obvious.
The second and last instruction is doing the same thing, but in a different way.
Here, we call the class
MyClass() directly as well as it’s method
hello(). Let’s check out what both prints:
# python /tmp/test.py Initiating the instance! Dan Inosanto Dan Inosanto
As we can see, both prints the same output. This means that :
myclass.hello(self) == MyClass.hello(myclass)
In general, we can say that:
<instance-name>.<method>(self) == <Class>.<method>(<instance-name>)
ie.. The keyword
self actually represents the instance being instantiated from the Class. Hence
self can be seen as Syntactic sugar.