0

I don't quite understand why the keyword self is necessary in the __init__() method in python.

class Test:
    def __init__(self):
        print("Test")

I understand that 'self' represents the object, but for what reason do I need this in the 'constructor'? I mean, if it has do to with something going on in the background, why wouldn't you leave it out entirely since it's always required anyways?

Thanks in advance.

Gereon99
  • 677
  • 1
  • 7
  • 15
  • 1
    How would you write a useful constructor without having access to `self`? – Aran-Fey Nov 06 '18 at 08:22
  • Imagine you want to call `self._complex_init_function()` apart from `self._yet_another_complex_init_function()`. Also: `__init__` is where you're supposed to initialize members such as `self.name = name` etc .. – Stefan Falk Nov 06 '18 at 08:22
  • 1
    Read: [Python \_\_init\_\_ and self what do they do?](https://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do) – Austin Nov 06 '18 at 08:23
  • so the parameter "self" is the same when you e.g. write 'self.variable = variable'? – Gereon99 Nov 06 '18 at 08:24
  • No, `self.variable` is the member of your class - `variable` might be a parameter as in `__init__(self, variable):` e.g. `test = Test(variable=1337)` – Stefan Falk Nov 06 '18 at 08:25
  • In my humble opinion, you can only understand the *why* fully once you learned about descriptors and how functions are descriptors. I wanted to write something about this, but the question is closed now. – timgeb Nov 06 '18 at 08:27
  • 1
    `this` in c++ is implicit while `self` in python is explicit, I think this just a grammar, no need to go deep into – atline Nov 06 '18 at 08:30
  • @timgeb it's already there : https://wiki.python.org/moin/FromFunctionToMethod – bruno desthuilliers Nov 06 '18 at 08:31

0 Answers0