What is __init__ for in a class?
Options
- It deletes the object when the program does not need it any more
- It runs when an object is created, to set its starting attributes (Correct option)
- It runs only once, when the whole program starts up
- It imports the modules that the class needs in order to work
Answer
It runs automatically when a new object is created, to set its starting attributes
Why
Writing Dog("Rex") creates a new Dog object and then automatically calls __init__(self, "Rex").
Inside it you usually store the values on the object: self.name = name.
Think of it as the setup step for every new object.
class Dog:
def __init__(self, name):
self.name = name
rex = Dog("Rex")
print(rex.name) # RexRemember
__init__ = setup that runs for every new object.