Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære The __init__ Method and self | Class Structures
Object Oriented Programming with Python

The __init__ Method and self

Stryg for at vise menuen

When you create a new object from a class in Python, the initialization process begins with a special method called __init__. The main job of __init__ is to set up the initial state of the object by assigning values to its attributes. Whenever you instantiate a class, Python automatically calls __init__ with the new object as its first argument.

The first parameter of every instance method, including __init__, is always named self by convention. self represents the instance being created or operated on. It allows you to store data that is unique to each object, rather than sharing it across all instances of the class. When you pass arguments during instantiation, those arguments are mapped to the parameters of the __init__ method. Inside the method, you can assign these values to attributes using self.attribute_name = value.

For example, if your class represents a bank account, you might want to store the account holder's name and the starting balance for each new account. By using self, you ensure that each object keeps track of its own data, and changes to one object do not affect others.

12345678910111213
class BankAccount: def __init__(self, holder_name, balance): self.holder_name = holder_name self.balance = balance # Creating two different accounts with unique data account1 = BankAccount("Alice", 1000) account2 = BankAccount("Bob", 500) print(account1.holder_name) print(account1.balance) print(account2.holder_name) print(account2.balance)

1. What is the primary role of the __init__ method in a Python class?

2. What is the significance of the self parameter in Python instance methods?

question mark

What is the primary role of the __init__ method in a Python class?

Vælg det korrekte svar

question mark

What is the significance of the self parameter in Python instance methods?

Vælg alle korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 3
some-alt