Sobes.tech
Junior — Middle

How does the self object pass the current class instance in Python methods?

sobes.tech AI

Answer from AI

In Python, self is a reference to the current instance of the class, which is explicitly passed to class methods. When you call a method through an object, Python automatically passes this object as the first argument to the method.

Example:

class MyClass:
    def greet(self, name):
        print(f"Hello, {name}! I am object {self}.")

obj = MyClass()
obj.greet("World")  # Inside greet, self will refer to obj

Here, self allows the method to access the attributes and other methods of the current object. It is not a keyword, but a convention, and its use is recommended.