All Courses

What is Self in python Oops

By Manerushi149@gmail.com, 3 months ago
  • Bookmark
0

What is Self in python Oops

Python
Oops
2 Answers
0
Hitendradixit18@gmail.com

Self is used to represent an instance of object

0
Goutamp777

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.

Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More