Python 魔法函数 - AI生成

Python的魔法函数是以双下划线__开头和结尾的特殊函数,它们构成了Python面向对象编程的核心,让你可以自定义对象的行为(比如加减运算、打印、迭代等)。这些函数不需要手动调用,而是在特定场景下由Python解释器自动触发。下面我会按功能分类整理最常用的魔法函数,并给出简单示例,方便你理解和使用。


一、构造与初始化类

这类魔法函数用于对象的创建、初始化和销毁,是最基础也最常用的。

魔法函数 触发场景 作用
__init__(self, ...) 实例化对象时(obj = Class() 初始化对象属性(构造方法)
__new__(cls, ...) 创建对象实例时(在__init__之前) 控制对象的创建过程(如单例模式)
__del__(self) 对象被垃圾回收时 释放资源(类似析构函数,不推荐依赖)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Person:
# __new__ 是创建实例的第一步
def __new__(cls, name):
print(f"创建{name}的实例")
return super().__new__(cls)

# __init__ 初始化实例属性
def __init__(self, name):
self.name = name

# __del__ 垃圾回收时触发
def __del__(self):
print(f"{self.name}的实例被销毁")

p = Person("张三") # 输出:创建张三的实例
del p # 输出:张三的实例被销毁

二、字符串表示与格式化

这类函数控制对象转换为字符串的行为,方便调试和展示。

魔法函数 触发场景 作用
__str__(self) print(obj) / str(obj) 面向用户的友好字符串表示
__repr__(self) repr(obj) / 交互式解释器显示 面向开发者的精确字符串表示(可还原对象)
__format__(self, format_spec) format(obj, spec) / f"{obj:spec}" 自定义格式化规则

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Book:
def __init__(self, title, price):
self.title = title
self.price = price

# 面向用户的展示
def __str__(self):
return f"《{self.title}》(价格:{self.price}元)"

# 面向开发者的精确表示
def __repr__(self):
return f"Book(title='{self.title}', price={self.price})"

b = Book("Python入门", 59.9)
print(b) # 输出:《Python入门》(价格:59.9元)
print(repr(b)) # 输出:Book(title='Python入门', price=59.9)

三、算术/比较运算符重载

这类函数让自定义对象支持加减、大小比较等运算符,是Python“运算符重载”的核心。

1. 算术运算符

魔法函数 触发场景 对应运算符
__add__(self, other) self + other 加法
__sub__(self, other) self - other 减法
__mul__(self, other) self * other 乘法
__truediv__(self, other) self / other 真除法
__floordiv__(self, other) self // other 整数除法
__mod__(self, other) self % other 取模

2. 比较运算符

魔法函数 触发场景 对应运算符
__eq__(self, other) self == other 等于
__ne__(self, other) self != other 不等于
__lt__(self, other) self < other 小于
__le__(self, other) self <= other 小于等于
__gt__(self, other) self > other 大于
__ge__(self, other) self >= other 大于等于

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

# 重载加法:Point(1,2) + Point(3,4) = Point(4,6)
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
raise TypeError("只能和Point对象相加")

# 重载等于判断
def __eq__(self, other):
return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y) # 输出:4 6
print(p1 == p2) # 输出:False

四、容器/序列行为

这类函数让自定义对象支持列表、字典等容器的操作(如索引、长度、遍历)。

魔法函数 触发场景 作用
__len__(self) len(obj) 返回容器的长度
__getitem__(self, key) obj[key] / 索引/切片 获取元素
__setitem__(self, key, value) obj[key] = value 设置元素
__delitem__(self, key) del obj[key] 删除元素
__iter__(self) for x in obj / iter(obj) 返回迭代器(配合__next__
__next__(self) 迭代器的next() 迭代时返回下一个元素
__contains__(self, item) item in obj 判断元素是否存在

示例:自定义简易列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyList:
def __init__(self):
self.items = []

def __len__(self):
return len(self.items)

def __getitem__(self, index):
return self.items[index]

def __setitem__(self, index, value):
self.items[index] = value

def __iter__(self):
# 直接复用列表的迭代器
return iter(self.items)

ml = MyList()
ml.items = [1,2,3]
print(len(ml)) # 输出:3
print(ml[0]) # 输出:1
ml[1] = 10
for x in ml:
print(x) # 输出:1 10 3

五、上下文管理器(with语句)

这类函数让对象支持with语句,实现自动资源管理(如文件、数据库连接)。

魔法函数 触发场景 作用
__enter__(self) 进入with代码块时 获取资源(返回值赋值给as后的变量)
__exit__(self, exc_type, exc_val, exc_tb) 退出with代码块时 释放资源(处理异常)

示例:模拟文件上下文管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MyFile:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None

def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file

def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# 返回True表示处理异常(不向外抛出),False则抛出
return False

# 使用with自动管理文件
with MyFile("test.txt", "w") as f:
f.write("Hello Python")
# 退出with后,文件自动关闭

六、其他常用魔法函数

魔法函数 触发场景 作用
__call__(self, ...) obj() / obj(args) 让对象可以像函数一样被调用
__hash__(self) hash(obj) 返回对象的哈希值(用于字典键、集合)
__bool__(self) bool(obj) / 条件判断 返回对象的布尔值(如if obj:

示例:可调用对象

1
2
3
4
5
6
7
class Calculator:
def __call__(self, a, b):
return a + b

calc = Calculator()
result = calc(10, 20) # 像函数一样调用对象
print(result) # 输出:30

总结

  1. Python魔法函数以__开头结尾,由解释器自动触发,无需手动调用,是自定义对象行为的核心。
  2. 常用分类:构造初始化(__init__/__new__)、字符串表示(__str__/__repr__)、运算符重载(__add__/__eq__)、容器行为(__len__/__getitem__)、上下文管理(__enter__/__exit__)。
  3. 核心原则:魔法函数的目的是让自定义对象“像Python内置对象一样工作”,遵循Python的设计风格(Pythonic),避免滥用(如无意义的运算符重载)。

Python 魔法函数 - AI生成
https://blog.carlvictor.cn/posts/8a901fa3.html
作者
Carl Victor
发布于
2026年8月27日
许可协议