Forum Archive

What is __init__?

Python567

In a class I start a funktion with __init__ why? I don‘t understand that really.

cvp

@Python567 read here

Python567

@cvp That is, if I write def __init will this one function or all functions be executed

cvp

@Python567 this linked doc says clearly:

When a class defines an init() method, class instantiation automatically invokes init() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:

x = MyClass()
Of course, the init() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to init(). For example,

class Complex:
... def init(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
x = Complex(3.0, -4.5)
x.r, x.i
(3.0, -4.5)

ccc

https://www.geeksforgeeks.org/__init__-in-python/

https://stackoverflow.com/questions/53318475/why-do-we-need-init-to-initialize-a-python-class

https://docs.python.org/3/reference/datamodel.html#object.__init__