Repaso
EspaƱol
PythonCorePY-53

What is __init__ for in a class?

Options

  1. It deletes the object when the program does not need it any more
  2. It runs when an object is created, to set its starting attributes (Correct option)
  3. It runs only once, when the whole program starts up
  4. 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)   # Rex

Remember

__init__ = setup that runs for every new object.

Key terms

Practice this question in Repaso