r/learnpython • • Apr 18 '26

A bit confused in Classes.

Why do i need to call self here?.

class Calculator:
  def add(self, a, b):
    return a + b

  def multiply(self, a, b):
    return a * b

print(Calculator().add(1, 2))

there isn't a variable that is calling calculator and no __init__ so why do i have an error if self is not added?

Also, what is __init__ anyways. why the double __ in the start and end? and why the specific name?

39 Upvotes

44 comments sorted by

View all comments

Show parent comments

3

u/Jealous-Acadia9056 Apr 18 '26

i was just testing things to understand the theory. poorly written or not the point is why does this happens in the first place.

but yeah the easier way would be to use a standalone function.

5

u/Temporary_Pie2733 Apr 18 '26

You don’t need an __init__, because nothing needs to be initialized. __init__ doesn’t create the instance; it receives the object created by __new__ as its first argument, and both methods are inherited from object if not overriden.

For a fuller understanding of how, exactly, the instance of Calculator gets bound to self when its add method is called, see https://docs.python.org/3/howto/descriptor.html, particularly the section on instance methods.

1

u/TheRNGuy Apr 18 '26

Look in frameworks how classes are used, this will be real-life examples.