World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
Self is used to represent an instance of object
In Python, the self
keyword is used to represent the instance of an object in a class method. It is used to distinguish between instance variables and local variables, and it allows you to access the attributes and methods of the instance from within the class.
For example, consider the following class:
class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, my name is {self.name}") obj = MyClass("John") obj.greet() # Output: "Hello, my name is John"
In the greet
method, self
refers to the obj
instance of the MyClass
class. It is used to access the name
attribute of the instance and include it in the greeting message.
When you call a method on an instance, Python automatically passes the instance as the first argument to the method. So, when you call obj.greet()
, Python internally calls MyClass.greet(obj)
. This is why you need to include self
as the first parameter in the method definition.