Python的魔法方法(Magic Methods),又称特殊方法或双下方法(Dunder Methods),是类中以双下划线(__
)开头和结尾的方法,用于自定义类的行为,使其支持Python内置操作(如运算符、迭代、上下文管理等)。
1. 对象生命周期控制
-
__new__(cls[, ...])
创建实例时首先调用,返回新对象(通常配合super().__new__
使用)。
示例:单例模式实现class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance -
__init__(self[, ...])
初始化实例属性,在__new__
之后自动调用45。
示例:构造方法class Person:
def __init__(self, name):
self.name = name # 初始化属性 -
__del__(self)
对象销毁时调用,用于资源清理(如关闭文件)35。
2. 字符串表示与格式化
-
__str__(self)
定义print(obj)
或str(obj)
的输出(用户友好)78。 -
__repr__(self)
定义repr(obj)
或交互式环境的输出(开发者友好)78。
示例:class Point:
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
3. 运算符重载
- 算术运算:
__add__(self, other)
(+
)、__sub__(self, other)
(-
)等79。 - 比较运算:
__eq__(self, other)
(==
)、__lt__(self, other)
(<
)等39。
示例:向量加法class Vector:
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
4. 容器类型模拟
-
__len__(self)
:定义len(obj)
的行为310。 -
__getitem__(self, key)
:定义obj[key]
的取值311。 -
__iter__(self)
:使对象可迭代39。
5. 其他常用魔法方法
-
__call__(self[, ...])
:使实例可像函数一样调用(如obj()
)25。 -
__getattr__(self, name)
:访问不存在的属性时触发912。 -
__enter__
/__exit__
:实现上下文管理器(with
语句)39。
设计哲学与注意事项
- 隐式调用:魔法方法由Python解释器在特定场景自动触发,无需显式调用23。
- 继承机制:多数魔法方法继承自
object
类,可重写以定制行为15。 - 慎用原则:过度使用可能降低代码可读性,适合需要与内置类型交互的场景910。
通过合理使用魔法方法,开发者可以构建高度集成的自定义类,实现Python的“万物皆对象”哲学1213。