0

In my class:

class MyClass:
    def __init__(self):
        self.title = None

How does python "know" to pass MyClass as the first argument to init when doing:

MyClass()

Likewise, if I had a classmethod, how would python "know" to pass MyClass as the first argument (cls) in that as well?

Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
FI-Info
  • 635
  • 7
  • 16
  • 3
    It does **not** pass `MyClass` as the first argument. The `__new__` method instantiates the actual instance then `__init__` initialises it. See [this question](https://stackoverflow.com/questions/674304/why-is-init-always-called-after-new). – Selcuk Oct 14 '19 at 02:22
  • [this answer](https://stackoverflow.com/a/23944658/10746224) has an excellent explanation for what happens behind the scenes with `self`. – Lord Elrond Oct 14 '19 at 04:04

1 Answers1

0

It's simply how the interpreter (or compiler) is written. It is the job of the interpreter (or compiler) to recognize that

MyClass()

is supposed to initialize a MyClass object and call the __init__ method with the newly created object as the self parameter. Note that, as one of the comments noted, it is the new object which is assigned to the self parameter, and not MyClass.

In the case where you're calling a non-initializer method, the interpreter (or compiler) likewise knows that you're calling a method, so it puts the object as the first argument.

Daniel Nguyen
  • 419
  • 2
  • 7