Python self

The self parameter is often used in object orientated programming.

The self parameter is added inside class methods, but why?

It’s a reference to the the object. That may sound vague, so let me explain.

Let’s say you have a class Animal with two instances: Cat and Dog. The self keyword now refers to the object.

Related course: Python Beyond the Basics – Object-Oriented Programming

Self code example

An object may be created with:

Then how would we set it’s name?

OK, so we call the method setName that’s defined in the class Animal.

Inside the class we need to somehow tell the objects name to be ‘Sally’, we do that with the self keyword.

This is dynamic. It works for other objects too.

Previous Post
Next Post

Leave a Reply