Nearby lessons

102 of 159

Python - self Variable

📌 What You Will Learn
  • Understand what self represents inside a class
  • Know where self is used: constructors and instance methods
  • Access instance variables and methods using self
  • Remember that self must always be the first parameter

What Is self?

self is the reference to the current object inside a class.

It is used to access instance variables and instance methods.

Where Is It Used?

  • Inside constructors
  • Inside instance methods

Example

Inside the constructor, self.name stores the name in the current object, so each object keeps its own value.

🐍Code Cell
1class Student:
2 def __init__(self, name):
3 self.name = name
4 
5 def display(self):
6 print("Hello", self.name)
7 
8 
9s1 = Student("Durga")
10s1.display()
Output
Hello Durga

Important Note

self should always be the first parameter in instance methods and constructors.

Without self, Python cannot know which object the method is working with.

Summary

Term Meaning
selfCurrent object
Instance variableVariable tied to object
Instance methodMethod that uses self
📝 Key Takeaways
  • self is the reference to the current object inside a class
  • It is used to access instance variables and instance methods
  • self is used inside constructors and inside instance methods
  • It must always be the first parameter of an instance method or constructor

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6