All Courses

What is Self in python Oops

By, 3 months ago
  • Bookmark

What is Self in python Oops

2 Answers

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): = name
    def greet(self):
        print(f"Hello, my name is {}")

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


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