The __init__ Method and self
Svep för att visa menyn
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.
12345678910111213class 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?
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal