Sobes.tech
Junior — Middle

Can you explain what the term 'self' means in the context of object-oriented programming?

sobes.tech AI

Answer from AI

In Python, self is a reference to the current instance of the class, through which you can access the attributes and other methods of this object inside methods.

When you define a method in a class, the first parameter should always be self (although the name can be different, but by convention, self is used). When calling a method on an object, Python automatically passes a reference to this object as the self parameter.

Example:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, my name is {self.name}")

p = Person("Anya")
p.greet()  # Outputs: Hello, my name is Anya

Here, self.name is an attribute of the specific object p. Without self, methods would not know which object they are working with.