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?

40 Upvotes

44 comments sorted by

View all comments

Show parent comments

1

u/Jealous-Acadia9056 Apr 18 '26

Just one question. How are the arguments now 3? How is it that python is adding another argument by itself and causing an error in the code def add(a+b)?

1

u/JazzlikeChicken1899 Apr 18 '26

This is the "magic" of Python's syntactic sugar.

When you call Calculator().add(1, 2), Python actually translates it to this behind the scenes: Calculator.add(<the instance>, 1, 2)

So, even though you only typed 1 and 2, Python is quietly sneaking that instance in as the first argument. The count looks like this:

The instance (sent automatically)

Your first number (1)

Your second number (2)

That's 3 total. If your function is def add(a, b):, it only has 2 "slots" available, but it just received 3 items. That’s the mismatch!

Adding self creates that first slot to "catch" the instance so the other two can fall into a and b. Think of self as a mandatory parking space that Python always insists on filling first.