Sobes.tech
Junior — Middle

Can you explain what the keyword self means inside a class method?

sobes.tech AI

Answer from AI

In Python, the keyword self inside a class method is used to refer to the current instance of that class. This allows access to the object's attributes and other methods.

For example, when you call an object's method, Python automatically passes this object as the first argument to the method, which by convention is called self:

class Person:
    def __init__(self, name):
        self.name = name  # self.name is an instance attribute

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

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

Thus, self links methods to a specific object, allowing interaction with its state.

Can you explain what the keyword self means inside a… - sobes.tech