0
What is __init__ in python?
Hello everyone, hope you are enjoying your day so far. I recently stumbled on a special variable called "__init__". I don't know what it does exactly but my lucky guess is that it allows you to take the argument of a class and store it in "self"? Please give me some clarification on this. and when do I use it? All responses are much appreciated!
2 Antworten
+ 5
__init__ is a method, which is mandatory in all the classes.
When you first create an instance of any class, then __init__ method gets called. So, in that method, you can define what should python do when any instance is being created
+ 3
__init__ is just a method, a reserved method, in Python. It's also called constructor. It gets invoked automatically whenever a new instance of a class is created.
You can use __init__ to Initialize some attributes of the class( i.e. When you do, self.something= something).
Its not mandatory to write one on every class. If not defined explicitly, default constructor will be called during instantiation.