0

I understand that self is a convention used to define the first argument in class methods, but since self itself is not a keyword, how can it be used with the '.' notation? As per my understanding only classes or instances are used to invoke a variable or method.

Even if 'self' is not a keyword, is it an object?

For eg consider

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

        def speak(self):
            print(f"Hello {self.name}")

s = Something("blah")
s.speak()

How does self.name work? Is the first argument to method of class an object?

The same example would work with 'this' instead of 'self'

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

        def speak(self):
            print(f"Hello {self.name}")

s = Something("blah")
s.speak()
tanvi
  • 27
  • 4

1 Answers1

2

Under the hood, self is just a regular variable that is passed as an argument to the methods of a class. When a method is called on an instance of a class, the instance is passed to the self-parameter of the method. This allows the method to access the attributes and other methods of the instance.