Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python self method

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python self method

Python self method

In Python, when you’re working with classes, there’s one keyword you’ll see in almost every method — and that’s self.

Let’s break it down simply:

The self keyword refers to the current object of the class. It’s how Python knows which object’s data you’re working with inside a method.

Why Use self?

When a method is defined inside a class, Python needs a way to connect that method to the specific object that calls it. That’s what self does — it carries the data of the object that’s using the method.

You must include self as the first parameter of every instance method.

A Real Example
				
					class Profile:
    name = "Zainab"
    age = 21

    def show(self):
        print("My name is", self.name, "and I am", self.age, "years old.")


				
			

Now let’s create an object and call the method:

				
					person = Profile()
person.show()

				
			

Output:

				
					My name is Zainab and I am 21 years old.

				
			

In this example:

  • self.name and self.age refer to the data inside the object person.

  • When we call person.show(), Python passes the person object as self to the show method automatically.

Summary

Whenever you define a method inside a class, use self to access the properties and methods of the object that calls it. It’s how Python keeps track of which object is doing what.

Scroll to Top