`self` in Python – Object Oriented Programming


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.

In short, 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.

The function hello() just prints the name value that is passed while instantiating the class MyClass().

We instantiate the class MyClass() as 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..

myclass.hello()

This should print the name we passed while instantiating MyClass() as myclass , which should be pretty obvious.

The second and last instruction is doing the same thing, but in a different way.

MyClass.hello(myclass)

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.

2 thoughts on “`self` in Python – Object Oriented Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s