乐闻世界logo
搜索文章和话题

What is init in Python?

1个答案

1

The __init__ method in Python is a special method (often referred to as a constructor) used to initialize newly created objects. It is automatically invoked when a new instance of a class is created. This method allows programmers to set the initial state of an object or assign initial values to its attributes.

Here is a simple example demonstrating the usage of the __init__ method:

python
class Person: def __init__(self, name, age): self.name = name self.age = age # Create an instance of the Person class person1 = Person("Alice", 30) # Now the name and age attributes of person1 have been initialized print(person1.name) # Output: Alice print(person1.age) # Output: 30

In this example, the Person class has two attributes: name and age. The __init__ method receives three parameters: self, name, and age. self is a reference to the current instance, while name and age are the parameters passed to the __init__ method, used to set the values for the name and age attributes. When creating an instance of the Person class, we pass "Alice" and 30 to the __init__ method, which are used to initialize the attributes of the instance.

2024年8月9日 09:42 回复

你的答案