new 方法的核心角色是创建并返回类的实例,控制对象的创建过程。它在实例化时先于 init 被调用,负责内存分配与实例生成,决定对象的类型,可实现单例、不可变对象等高级模式。

在Python的面向对象编程中,
__new__
__init__
__new__
__init__
__new__
__init__
面向对象编程中,当我们通过
ClassName()
__new__
@classmethod
cls
__init__
一旦
__new__
__init__
__init__
self
__new__
self
打个比方,
__new__
__init__
class MyClass:
def __new__(cls, *args, **kwargs):
print("--- __new__ 方法被调用 ---")
# 通常这里会调用父类的 __new__ 方法来实际创建实例
instance = super().__new__(cls)
print(f"--- __new__ 创建了实例: {instance} ---")
return instance
def __init__(self, name):
print("--- __init__ 方法被调用 ---")
self.name = name
print(f"--- __init__ 初始化了实例 {self},名称为: {self.name} ---")
# 实例化一个对象
obj = MyClass("Python")
print(f"最终对象: {obj}, 名称: {obj.name}")从输出中可以清晰地看到
__new__
__init__
__new__
在我看来,
__new__
__new__
cls
__init__
self
__new__
super().__new__(cls)
__new__
__new__
__init__
__new__
cls
__new__
__new__
说白了,如果你想在对象被真正“出生”之前做一些事情,或者想控制对象的“出生方式”,那么
__new__
class Singleton:
_instance = None # 用于存储单例实例
def __new__(cls, *args, **kwargs):
if cls._instance is None:
print("--- 首次创建单例实例 ---")
cls._instance = super().__new__(cls)
else:
print("--- 返回已存在的单例实例 ---")
return cls._instance
def __init__(self, name):
# 注意:__init__ 每次都会被调用,所以这里需要一些判断
# 或者确保 __init__ 是幂等的
if not hasattr(self, '_initialized'): # 避免重复初始化
print(f"--- 初始化单例实例: {name} ---")
self.name = name
self._initialized = True
else:
print(f"--- 单例实例已初始化,跳过重复初始化: {name} ---")
s1 = Singleton("InstanceOne")
print(f"s1 的名称: {s1.name}, ID: {id(s1)}")
s2 = Singleton("InstanceTwo") # 此时 __init__ 也会被调用,但 __new__ 返回的是s1
print(f"s2 的名称: {s2.name}, ID: {id(s2)}")
s3 = Singleton("InstanceThree")
print(f"s3 的名称: {s3.name}, ID: {id(s3)}")
print(f"s1 is s2: {s1 is s2}")
print(f"s1 is s3: {s1 is s3}")这个例子清楚地展示了
__new__
__init__
__init__
__init__
__new__
self
self
__new__
__init__
__init__
self
__init__
self.name = name
self.age = age
__init__
__init__
super().__init__(*args, **kwargs)
__init__
None
self
__init__
class Car:
def __init__(self, brand, model, year, color="白色"):
# 验证输入,确保数据有效性
if not isinstance(brand, str) or not brand:
raise ValueError("品牌不能为空且必须是字符串")
if not isinstance(year, int) or year < 1900 or year > 2024:
raise ValueError("年份必须是有效的整数")
self.brand = brand
self.model = model
self.year = year
self.color = color
self.engine_started = False # 默认引擎未启动
print(f"--- {self.brand} {self.model} (年份: {self.year}, 颜色: {self.color}) 已成功初始化 ---")
def start_engine(self):
if not self.engine_started:
self.engine_started = True
print(f"{self.brand} {self.model} 引擎启动!")
else:
print(f"{self.brand} {self.model} 引擎已在运行。")
# 正常创建对象
my_car = Car("Tesla", "Model 3", 2023, "蓝色")
my_car.start_engine()
# 尝试创建带有无效参数的对象
try:
bad_car = Car("Ford", "Focus", 1890)
except ValueError as e:
print(f"创建失败: {e}")
try:
another_bad_car = Car("", "Fiesta", 2020)
except ValueError as e:
print(f"创建失败: {e}")通过
__init__
Car
__new__
虽然大多数时候我们只需要关心
__init__
__new__
实现单例模式(Singleton Pattern): 这是最常见的需要重写
__new__
__new__
__new__
创建不可变对象(Immutable Objects): 虽然Python本身提供了元组、字符串等不可变类型,但如果你想创建自定义的不可变类,
__new__
__new__
__setattr__
__delattr__
__new__
改变实例的类型: 这是一个比较高级且不常用的技巧,但
__new__
cls
class Base:
def __new__(cls, type_name):
if type_name == "special":
print("--- __new__ 返回 SpecialClass 实例 ---")
return super().__new__(SpecialClass) # 返回不同类型的实例
else:
print("--- __new__ 返回 Base 实例 ---")
return super().__new__(cls)
def __init__(self, type_name):
self.type = type_name
print(f"--- Base 或其子类实例初始化: {self.type} ---")
class SpecialClass(Base):
def __init__(self, type_name):
super().__init__(type_name)
self.special_attribute = "我是特殊的!"
print(f"--- SpecialClass 额外初始化 ---")
obj1 = Base("normal")
print(f"obj1 类型: {type(obj1)}, 属性: {obj1.type}")
obj2 = Base("special")
print(f"obj2 类型: {type(obj2)}, 属性: {obj2.type}")
if isinstance(obj2, SpecialClass):
print(f"obj2 拥有特殊属性: {obj2.special_attribute}")这个例子展示了
Base
__new__
Base
SpecialClass
元类编程(Metaclass Programming): 在更深层次的Python编程中,元类(metaclass)是用来创建类的类。当一个元类被调用来创建新的类时,它的
__new__
总的来说,当你需要对对象的“出生”过程本身进行干预,而不是仅仅对出生后的对象进行“装修”时,
__new__
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号