__init__ (Constructor)
noun
say it: “DUN-der IN-it” /ˈdʌndər ˈɪnɪt/ or “kun-STRUK-ter” /kənˈstrʌktər/
The method Python runs by itself when an object is made from a class; it sets up the object's starting data, such as an account's owner and balance.
What does __init__ do?
__init__ runs automatically when you create an object. It sets up the object's starting data.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
account = BankAccount("Nia", 100)
print(account.balance) # 100
In a sentence
- “The __init__ method sets self.owner and self.balance for each new account.”
- “BankAccount("Nia", 100) calls __init__ with "Nia" and 100.”
Level: Journeyman · More Python terms at this level
Updated