I. What Is a Constructor Method
In object-oriented programming, the construction process usually refers to the process of creating an object and bringing it into a usable initial state.
In Python, two concepts need to be distinguished:
- Object creation: allocating and creating a new object, mainly handled by
__new__(). - Object initialization: setting the object's initial attributes and state, mainly handled by
__init__().
In Python, __init__() is often called a constructor method, but from the perspective of a strict object model it is actually an initialization method, not the method responsible for creating the object.
Let's look at a simple example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name)
print(person.age)
Output:
Alice
25
When Person("Alice", 25) is executed, Python completes the object creation and initialization process, ultimately producing an instance with the name and age attributes.
II. The Complete Process of Object Creation and Initialization
To understand __init__(), you first need to understand the call process when Python creates an instance.
When you execute:
person = Person("Alice", 25)
Python does not directly call __init__() to create the object; instead, it completes a series of operations through the class's call mechanism.
For the usual class instance creation process, this can be simplified as:
flowchart TD
A["Call class Person"] --> B["Execute Person.__new__"]
B --> C["Create and return instance"]
C --> D{"Does the returned object belong to Person or its subclass?"}
D -->|Yes| E["Execute Person.__init__"]
D -->|No| F["Skip Person.__init__"]
E --> G["Initialize instance attributes"]
G --> H["Return instance"]
F --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There are two key methods here:
| Method | Main responsibility | Responsible for creating the instance |
|---|---|---|
__new__() |
Create and return the instance | Yes |
__init__() |
Initialize the already-created instance | No |
1. __new__(): Responsible for Creating the Object
__new__() is a special method, and a default implementation is usually provided by the object base class.
It receives the class object as its first parameter, usually named cls, and returns an instance.
class Person:
def __new__(cls, *args, **kwargs):
print("执行 __new__")
instance = super().__new__(cls)
return instance
def __init__(self, name):
print("执行 __init__")
self.name = name
person = Person("Alice")
Output:
执行 __new__
执行 __init__
Here:
instance = super().__new__(cls)
calls the parent class's object creation logic to create an instance of the current class.
The object returned by __new__() determines whether the current class's __init__() is subsequently called.
2. __init__(): Responsible for Initializing the Object
__init__() runs after the object is created, and is typically used to:
- Set instance attributes.
- Initialize the object's internal state.
- Store the arguments passed in at construction time.
- Set up the data structures the object needs to maintain.
- Validate that the initialization arguments meet the requirements.
For example:
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
product = Product("Keyboard", 299, 100)
print(product.name)
print(product.price)
print(product.stock)
Output:
Keyboard
299
100
Here, __init__() is responsible for establishing the initial state of the instance.
III. Basic Syntax of init()
__init__() is a special method in a Python class, and its basic form is as follows:
class ClassName:
def __init__(self, parameters):
self.attribute = value
Its main components:
| Component | Description |
|---|---|
__init__ |
The name of the special method |
self |
The instance currently being initialized |
| Parameter list | Receives the arguments passed in when the instance is created |
| Method body | Sets the instance attributes and initial state |
1. The Role of self
self represents the current instance object.
It is not a Python keyword, but rather a parameter name established by convention in the Python community.
class Student:
def __init__(self, name):
self.name = name
student = Student("Tom")
Execution:
student = Student("Tom")
can be understood conceptually as:
student = Student.__new__(Student)
Student.__init__(student, "Tom")
The code here is a simplified expression to help you understand the calling relationship; it is not equivalent to Python's complete class invocation implementation.
In __init__():
self.name = name
means storing the value of the parameter name into the attribute name of the current instance.
2. The Difference Between self.name and name
class Student:
def __init__(self, name):
name = name
self.name = name
These two lines of code do completely different things:
name = name
merely rebinds the local variable name to its original value, and does not create an attribute for the instance.
Whereas:
self.name = name
is what actually stores the data as an instance attribute.
You can verify this through the instance:
student = Student("Tom")
print(student.name)
Output:
Tom
If you only write name = name, accessing student.name will raise an AttributeError.
IV. Designing the Parameters of init()
Like ordinary Python functions, __init__() can use different types of parameters.
1. Required Parameters
class User:
def __init__(self, username, email):
self.username = username
self.email = email
user = User("alice", "alice@example.com")
When creating an instance, the required parameters must be provided.
If a parameter is missing:
user = User("alice")
This will raise a TypeError because the email argument is missing.
2. Default Parameters
Default values can make some initialization parameters optional.
class User:
def __init__(self, username, role="user", active=True):
self.username = username
self.role = role
self.active = active
user1 = User("alice")
user2 = User("bob", "admin", False)
Different instances can have different initial states.
3. Keyword Arguments
When initializing, you can pass arguments by keyword to improve code readability.
class Database:
def __init__(self, host, port, username):
self.host = host
self.port = port
self.username = username
db = Database(
host="localhost",
port=5432,
username="admin"
)
Keyword arguments can reduce confusion among multiple parameters of the same type.
4. Variable Arguments
When the number of initialization arguments is not fixed, you can use *args and **kwargs.
class Configuration:
def __init__(self, *args, **kwargs):
self.values = args
self.options = kwargs
config = Configuration(
"development",
"debug",
host="localhost",
port=8000
)
print(config.values)
print(config.options)
Output:
('development', 'debug')
{'host': 'localhost', 'port': 8000}
However, in real projects, variable arguments should not be abused just for flexibility. Explicit parameter definitions are usually easier to understand, check, and maintain.
V. The Pitfall of Default Parameters and Mutable Objects
The default parameters of __init__() follow the parameter rules of ordinary Python functions.
Default parameter expressions are evaluated when the function is defined, not re-evaluated each time an instance is created.
Therefore, using mutable objects as default parameters can cause different instances to share the same object.
1. Incorrect Example
class Student:
def __init__(self, name, courses=[]):
self.name = name
self.courses = courses
student1 = Student("Alice")
student2 = Student("Bob")
student1.courses.append("Python")
print(student1.courses)
print(student2.courses)
Output:
['Python']
['Python']
The problem is that the default parameter list is created only once, and the courses attribute of multiple instances references the same list object.
2. Correct Way
Use None as the default value and create an independent list during initialization.
class Student:
def __init__(self, name, courses=None):
self.name = name
self.courses = [] if courses is None else list(courses)
student1 = Student("Alice")
student2 = Student("Bob")
student1.courses.append("Python")
print(student1.courses)
print(student2.courses)
Output:
['Python']
[]
Here, this is used:
courses=None
as the default parameter, and then a new list is created during initialization.
list(courses) creates a new list, but only a shallow copy. If the list contains mutable objects internally, those internal objects may still be shared.
3. When Default Parameters Are Initialized
class Counter:
def __init__(self, values=[]):
self.values = values
The default parameters can be observed through the function object's __defaults__ attribute:
print(Counter.__init__.__defaults__)
The output is something like:
([],)
This shows that the default list is stored in the function object's default arguments, rather than being recreated on every instantiation.
6. init() and Instance Attributes
The most common use of __init__() is to create instance attributes.
1. Initializing Instance Attributes
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employee = Employee("Alice", 12000)
print(employee.__dict__)
Output:
{'name': 'Alice', 'salary': 12000}
For ordinary instances that do not use a special storage mechanism, self.name and self.salary are usually stored in the instance's attribute dictionary.
2. Each Instance Has Its Own Attributes
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
account1 = Account("Alice", 1000)
account2 = Account("Bob", 2000)
account1.balance += 500
print(account1.balance)
print(account2.balance)
Output:
1500
2000
The two instances each store their own balance; modifying the attribute of one instance does not automatically modify the other.
3. Instance Attributes and Class Attributes
class Employee:
company = "OpenTech"
def __init__(self, name):
self.name = name
employee1 = Employee("Alice")
employee2 = Employee("Bob")
print(employee1.company)
print(employee2.company)
Output:
OpenTech
OpenTech
Here:
companyis a class attribute.nameis an instance attribute.__init__()is usually responsible for initializing instance attributes.- Class attributes are generally declared in the class definition.
Note that when an instance accesses an attribute, it first looks in the instance's own attributes, then continues the lookup through the class and its inheritance hierarchy according to the attribute lookup rules.
7. init() in Inheritance
In an inheritance relationship, a subclass can define its own __init__().
But if the subclass overrides the parent class's __init__(), the parent class's initialization method will not run automatically.
1. Subclass Overriding init()
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
self.name = name
self.breed = breed
dog = Dog("Buddy", "Golden Retriever")
print(dog.name)
print(dog.breed)
Here the subclass reimplements the initialization logic.
However, when the parent class's initialization logic is fairly complex, writing it out again directly leads to code duplication.
2. Using super() to Call the Parent Class Initializer
It is recommended to use super() to reuse the parent class's initialization logic.
class Animal:
def __init__(self, name):
self.name = name
self.alive = True
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Buddy", "Golden Retriever")
print(dog.name)
print(dog.alive)
print(dog.breed)
Output:
Buddy
True
Golden Retriever
Executing:
super().__init__(name)
will call the next applicable initializer according to the method resolution order (MRO).
In simple single inheritance, it usually manifests as calling the parent class's __init__().
3. Initialization in Multi-Level Inheritance
class Animal:
def __init__(self, name):
self.name = name
print("Animal 初始化")
class Mammal(Animal):
def __init__(self, name):
super().__init__(name)
self.warm_blooded = True
print("Mammal 初始化")
class Dog(Mammal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
print("Dog 初始化")
dog = Dog("Buddy", "Golden Retriever")
Output:
Animal 初始化
Mammal 初始化
Dog 初始化
Each layer delegates the initialization process to the next class in the MRO via super().
4. Multiple Inheritance and Cooperative Initialization
In multiple inheritance, super() is not simply equivalent to directly calling some fixed parent class.
It looks up the next method according to the MRO, so multiple parent classes should follow the cooperative initialization convention.
class NameMixin:
def __init__(self, name, **kwargs):
self.name = name
super().__init__(**kwargs)
class AgeMixin:
def __init__(self, age, **kwargs):
self.age = age
super().__init__(**kwargs)
class Person(NameMixin, AgeMixin):
def __init__(self, name, age, **kwargs):
super().__init__(name=name, age=age, **kwargs)
class Base:
def __init__(self, **kwargs):
if kwargs:
raise TypeError(f"Unexpected arguments: {kwargs}")
person = Person("Alice", 25)
print(person.name)
print(person.age)
Output:
Alice
25
The key points here are:
- Each layer continues the call via
super(). - Arguments are passed by keyword to avoid positional mismatches.
**kwargsis used to pass arguments that have not yet been consumed.- The base class ultimately checks whether there are any unprocessed arguments.
This pattern is called cooperative multiple inheritance initialization.
VIII. Differences Between init() and new()
__new__() and __init__() are both special methods in Python's object model, but their responsibilities are completely different.
| Comparison Dimension | __new__() |
__init__() |
|---|---|---|
| Core Responsibility | Create the object | Initialize the object |
| First Parameter | cls |
self |
| When Called | Before initialization | After the object is created |
| Return Value | Usually returns an instance | Must return None |
| Whether Often Overridden | Less often | Very common |
| Common Use | Control object creation | Set the initial state |