I. What Is Python Object Creation?
In Python, a class is not only a template that describes object attributes and behavior; it is also an object that can be called.
When the following is executed:
class Person:
pass
person = Person()
In fact, Person() is a class call. Python creates an instance through the class call mechanism and, under appropriate conditions, executes the initialization method.
Object creation involves three core concepts:
| Concept | Meaning | Main Responsibility |
|---|---|---|
| Class call | Using the class name followed by parentheses | Initiates the instance creation process |
__new__() |
Object creation method | Creates and returns an instance |
__init__() |
Object initialization method | Sets the initial state of the instance |
Pay special attention:
In Python, the method actually responsible for creating an object is __new__(), not __init__().
__init__() is only responsible for initializing an object that has already been created.
II. The Complete Process of Python Object Creation
When the following is executed:
person = Person()
Python handles this operation through the metaclass call mechanism.
For an ordinary class, the process can usually be understood as follows:
- Call the class's
__new__()method. __new__()creates and returns an object.- Determine whether the returned object belongs to the current class or its subclasses.
- If the type condition is met, call the current class's
__init__(). - After initialization is complete, the class call expression returns the instance.
The complete process is as follows:
flowchart TD
A["Call Person"] --> B["Enter the class call mechanism"]
B --> C["Call Person.__new__"]
C --> D["Create and return object"]
D --> E{"Returned object is Person or its subclass"}
E -->|Yes| F["Call Person.__init__"]
E -->|No| G["Skip __init__ of the current class"]
F --> H["Initialization complete"]
G --> I["Return object directly"]
H --> J["Class call expression ends"]
I --> J
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Two levels need to be distinguished here:
type.__call__()is responsible for controlling the class call process.- The class's
__new__()and__init__()are responsible for creating and initializing the object, respectively.
For an ordinary class, its metaclass is usually type, so the class call process can be understood as being coordinated by type.__call__().
III. Basic Syntax of new()
__new__() is a special method in Python and is mainly responsible for creating and returning an instance.
Basic syntax:
class ClassName:
def __new__(cls, *args, **kwargs):
instance = super().__new__(cls)
return instance
Parameter description:
| Parameter | Description |
|---|---|
cls |
The class for which an instance is about to be created |
*args |
Receives the positional arguments passed to the class call |
**kwargs |
Receives the keyword arguments passed to the class call |
| Return value | Usually an instance of the current class |
Unlike __init__(), the first parameter of __new__() is cls, not self.
The reason is:
clsrepresents the class object; at this point the instance has not yet been created.selfrepresents the already-created instance, used by the initialization method.
1. The Simplest new() Example
class Person:
def __new__(cls):
print("Executing __new__")
instance = super().__new__(cls)
return instance
def __init__(self):
print("Executing __init__")
person = Person()
Output:
Executing __new__
Executing __init__
Here:
instance = super().__new__(cls)
This calls the parent class's object-creation logic, which typically ends up using object.__new__() to create the instance.
Then:
return instance
This returns the created instance to the class-call mechanism.
If the returned object satisfies the instance-type condition of the current class, Python will proceed to call the corresponding initialization method.
2. Why new() Usually Needs to Return an Object
The core task of __new__() is to create and return an instance.
For example:
class Person:
def __new__(cls):
print("Creating a Person object")
return super().__new__(cls)
person = Person()
print(type(person))
Output:
Creating a Person object
<class '__main__.Person'>
If a custom __new__() does not return an instance but returns None, then the result of the class call will be None, and the current class's __init__() will not be executed either.
class Person:
def __new__(cls):
return None
def __init__(self):
print("Executing initialization")
person = Person()
print(person)
Output:
None
This shows that the return value of __new__() determines what object the class call ultimately produces.
IV. The Difference Between new() and init()
These two methods often appear together, but their responsibilities are completely different.
1. Comparison Table
| Comparison Dimension | __new__() |
__init__() |
|---|---|---|
| Method responsibility | Create the object | Initialize the object |
| First parameter | cls |
self |
| Call timing | Before initialization | After the object is created |
| Return value | Returns the created object | Must return None |
| Can it control the instance type | Yes | No |
| Is it often overridden | Rarely | Very commonly |
| Typical uses | Immutable types, custom creation mechanisms | Attribute assignment, state initialization |
2. Understanding the Execution Order Through Code
class Product:
def __new__(cls, name):
print("1. 创建对象")
instance = super().__new__(cls)
return instance
def __init__(self, name):
print("2. 初始化对象")
self.name = name
product = Product("Keyboard")
Output:
1. Create object
2. Initialize object
As you can see, __new__() executes first, and __init__() executes afterward.
3. init() cannot replace new()
The following code is incorrect:
class Person:
def __init__(self):
return "Alice"
Executing:
person = Person()
This will raise a TypeError.
The reason is that __init__() must return None; it cannot return another object to replace the current instance.
If you need to control object creation and the returned result, you should look into __new__().
V. Calling Rules for new()
To understand __new__(), you also need to understand its relationship with the class invocation mechanism.
1. new() does not always have to be explicitly defined
In Python, all ordinary classes inherit from object by default.
class Person:
pass
person = Person()
Although __new__() is not defined, Python can still create instances.
This is because the class can use the default object creation method inherited from object.
Usually, you do not need to override __new__() to create ordinary instances.
2. When new() returns an instance of the current class, init() will be executed
class Person:
def __new__(cls):
print("执行 new")
return super().__new__(cls)
def __init__(self):
print("执行 init")
person = Person()
Output:
Executing new
Executing init
Because the returned object belongs to Person, Person.__init__() continues to be executed.
3. When new() returns another type, initialization of the current class is skipped
class Person:
def __new__(cls):
print("执行 new")
return {"name": "Alice"}
def __init__(self):
print("执行 init")
person = Person()
print(person)
print(type(person))
Output:
Executing new
{'name': 'Alice'}
<class 'dict'>
Because __new__() returns a dictionary rather than an instance of Person or its subclasses, Person.__init__() is not executed.
This is also an important reason why __new__() can control the final type of the object.
4. Special case when a subclass instance is returned
The condition is not whether the object is exactly the same as the current class, but whether the object belongs to the current class or one of its subclasses.
class Animal:
def __new__(cls):
print("Animal.__new__")
return super().__new__(Dog)
def __init__(self):
print("Animal.__init__")
class Dog(Animal):
def __init__(self):
print("Dog.__init__")
animal = Animal()
print(type(animal))
Output:
Animal.__new__
Dog.__init__
<class '__main__.Dog'>
Here:
- What is called is
Animal(). Animal.__new__()returns aDoginstance.Dogis a subclass ofAnimal.- Therefore, Python executes
Dog.__init__()according to the actual type of the returned object.
This shows that the choice of initialization method depends on the object returned by __new__(), not just on the name of the class originally called.
VI. Why the first parameter of new() is cls
The first parameter of __new__() is the class object, because it is responsible for creating the instance.
class Person:
def __new__(cls, name):
print("当前类:", cls)
instance = super().__new__(cls)
return instance
def __init__(self, name):
self.name = name
person = Person("Alice")
Output:
当前类: <class '__main__.Person'>
Here, cls is the Person class itself.
By using:
super().__new__(cls)
The current class is passed to the parent class's creation logic, thereby creating an instance of the corresponding type.
If written as:
super().__new__(Person)
Although it may work normally in this simple example, it hard-codes the class name, which is not conducive to inheritance and reuse.
Using cls is recommended.
1. cls in inheritance
class Animal:
def __new__(cls):
print("当前创建类:", cls.__name__)
return super().__new__(cls)
class Dog(Animal):
pass
animal = Animal()
dog = Dog()
Output:
当前创建类: Animal
当前创建类: Dog
When the subclass Dog() is called, the cls received by the inherited __new__() is Dog.
Therefore:
super().__new__(cls)
It can create an instance of the correct type according to the class actually called.
VII. Application of new() to immutable types
One of the most typical use cases of __new__() is inheriting from immutable types and controlling instance values.
After an immutable object is created, its core value cannot be modified through ordinary assignment.
For example:
intstrtuplefrozenset
The values of these types need to be determined during the object creation stage, so when inheriting from immutable types, __new__() usually needs to be overridden.
1. Inheriting from str to create a custom string type
class UpperString(str):
def __new__(cls, value):
value = value.upper()
return super().__new__(cls, value)
text = UpperString("hello python")
print(text)
print(type(text))
Output:
HELLO PYTHON
<class '__main__.UpperString'>
Here:
return super().__new__(cls, value)
The converted string is passed to the creation logic of str.
The actual value of the string is already determined during the object creation stage.
2. Inheriting from int to create a constrained integer type
class PositiveInt(int):
def __new__(cls, value):
value = int(value)
if value < 0:
raise ValueError("数值不能为负数")
return super().__new__(cls, value)
number = PositiveInt(100)
print(number)
print(type(number))
Output:
100
<class '__main__.PositiveInt'>
If a negative number is passed in:
number = PositiveInt(-10)
This will raise ValueError.
Here, data conversion and validation are completed before the object is created.
3. Why You Can't Modify Immutable Values Only in init()
class UpperString(str):
def __init__(self, value):
self.value = value.upper()
text = UpperString("hello")
print(text)
print(text.value)
Output:
hello
HELLO
Although self.value is set to an uppercase string, text itself is still the original lowercase string.
The reason is that the actual string value of str has already been determined during the __new__() stage, and __init__() cannot reconstruct or replace the core value of an immutable string.
Therefore, when inheriting from an immutable type, you need to complete the construction of the core value in __new__().
8. Typical Use Cases of new()
__new__() is not common in ordinary business development, but it is very important in certain advanced scenarios.
1. Singleton Pattern
The goal of the singleton pattern is to limit the number of instances of a class, usually requiring that multiple calls to the class return the same instance.
This can be implemented using __new__():
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b)
Output:
True
Here:
if cls._instance is None:
cls._instance = super().__new__(cls)
The instance is actually allocated only on the first creation; afterward, the existing instance is returned directly.
However, this implementation still has two problems:
- Multiple calls to the class will still execute
__init__(). - When multiple threads create at the same time, race conditions may occur.
Solving the Repeated Initialization Problem
You can add an initialization flag:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if getattr(self, "_initialized", False):
return
self.value = 100
self._initialized = True
a = Singleton()
b = Singleton()
print(a is b)
print(a.value)
Output:
True
100
Here, _initialized is used to avoid executing the initialization logic repeatedly.
However, this is still not a complete thread-safe singleton implementation. In a multithreaded environment, additional synchronization mechanisms are needed, and you also need to consider issues such as whether subclasses share the instance, initialization failure, and test isolation.