What is the purpose of the self word in Python?

The self parameter is often used in object orientated programming, the self parameter is added inside class methods, in this article we’ll explain you why it exists.

It’s a reference to the the object. The reason you need to use self. is because Python uses this to refer to instance attributes.

Related course: Python Programming Courses & Exercises

Introduction

In object orientated programming, you can create many objects from a class.

Each object can have unique values for variables.

obj1 = Person()
obj2 = Person()
obj3 = Person()

Then set the objects variable(s):

obj1.name = "Sally"
obj2.name = "Sandra"
obj3.name = "Steve"

So visually like this:

create objects from class

What if you want to access an objects variables inside a class?

The class does not know which variable values belong to which object.

class Person:
# Who is Sally, Sandra or Steve?

By using the self variable, it can set or get the objects variables.

Python then knows it should access the variables for that objects.

The code below sets two variable values:

In a class they can be accessed by self.name, this referes to myself, i.e. the current object’s instance attribute.

class Person:
def meet(self):
print("I am " + self.name)

If an object calls .meet(), the object itself is passed as self as (hidden) argument.

python self refers to the object

>>> obj1.meet()
I am Sally

>>> obj2.meet()
I am Sandra

>>> obj3.meet()
I am Steve

If you are a Python beginner, then I highly recommend this book.

Self example

Recall that you can create objects from a class.

Given a class, you can create one or more unique objects.

An object may be created like this:

cat = Animal()

When you create an object from a class, the object itself is passed as a parameter (in the constructor).

See the word self in the constructor below.

python constructor self

class Animal:
def __init__(self):
pass

Thus, the object itself is passed.

If you were to create two objects, both would be passed as parameter in the constructor (self)

cat = Animal()
dog = Animal()

Because you pass the object itself as parameter in the constructor, the objects variables can be accessed with the self keyword.

If you have the class as defined below:

class Animal:
def __init__(self):
pass

def setName(self, name):
self.name = name

It has a method setName() which takes the object and the name variable.

Each time you call the method setName(), the object itself is passed.

what is Python self

The self keyword can be used to set the currents objects name, you can do this:

cat.setName("Bob")
dog.setName("Woof")

They look similar, but they are different.

The method setName() is called with a different name, but also with a different object.

The first call passes the object cat as hidden parameter (self).

cat.setName("Bob")

The second call passes the object dog as hidden parameter (self).

dog.setName("Woof")

If you output cat.name or dog.name you’ll see the objects variables have been changed inside the class.

If you are a Python beginner, then I highly recommend this book.

Can you skip the “self” variable?

The self keyword is used to access an objects variables. Can you skip this?

The short answer is, no.

If you try, it will throw an error:

>>> class Cat:
... def meow():
... print("meow")
...
>>> c = Cat()
>>> c.meow()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: meow() takes 0 positional arguments but 1 was given
>>>

That is because the function meow() accepts zero arguments but we provided one.

The object c itself is automatically passed as first argument.

That’s why self is required as argument in a class function.

>>> class Cat:
... def meow(self):
... print("meow")
...
>>> c = Cat()
>>> c.meow()

Because the object is passed as argument, you can access the objects variables.

>>> class Cat:
... name = ""
... def meow(self):
... print("I am " + self.name)
...
>>> c = Cat()
>>> c.name = "Bob"
>>> c.meow()
I am Bob

python self object

The self variable is bound to the current object.

The example below shows that:

class Car:
def __init__(self, brand):
self.brand = brand

def show(self):
print("This car is a " + self.brand)

You can create new objects:

obj1 = Car("Volvo")
obj2 = Car("Ferrari")

python create objects

Then when calling the show() method, the object is passed as hidden argument:

>>> obj1.show()
This car is a Volvo

>>> obj2.show()
This car is a Ferrari

In fact, the object is both passed when created (to the constructor) and when calling the method (setBrand).

The self keyword must be included for every class method.

Why not make self implicit?

In Python you must write self each time inside a class.

It requires explicit definition.

The philosophy of Python is “Explicit is better than implicit”.

the python zen

You can read more about that decision here.

self in other programming languages

In other programming languages you have something similar with a different syntax.

The Java programming language used this instead.

public class Cat {
int age;

// Constructor with a parameter
public Cat(int age) {
this.age = age;
}
}

Ruby uses the @ symbol.

#!/usr/bin/ruby

class Cat
def initialize(age)
@age = age
end

def show()
puts "Cats age is #@age"
end
end

bob = Cat.new 3
bob.show()

Al though they are syntactically different,

All object orientated programming languages refer to the objects data in a similar way.

It’s all for the same purpose: to access the objects variables within the class.

So Python’s self is similar to Java’s this, Ruby’s @ and C++ this.

similar variables for class method and static method

You learned about self before, which is for regular the default classes.

Now onto something different: class methods.

A class method can be called without creating objects, you call it directly on the class.

>>> class World:
... @classmethod
... def sun(cls):
... print("Sun shines")
...
>>> World.sun()
Sun shines

If you have a class method, you can use cls instead.

class Cat:
@classmethod
def jump(cls):
print("Cat is jumping")

Cat.jump()
Cat is jumping

Here cls refers to the classes variables, not object variables.

class Cat:
name = "Bob"
@classmethod
def jump(cls):
print("Cat " + cls.name + " is jumping")

Cat.jump()

This outputs Cat Bob is jumping.

For a static method, it is not required.

That’s because static method are just methods, they cannot access any of the classes variables or objects variables directly.

If you are a Python beginner, then I highly recommend this book.

Download exercises