python魔法方法

什么是魔法方法

Python 的魔法方法(Magic Methods),也叫特殊方法(Special Methods)或双下方法(dunder methods,因为名字前后都有双下划线 __),是 Python 类中预定义的一类方法,用于定义对象在特定操作下的行为。

当你使用像 +len()str()in[] 等语法时,Python 其实是在背后调用对应的魔法方法。

常见魔法方法举例

1. __init__:初始化对象

1
2
3
4
5
class Person:
def __init__(self, name):
self.name = name

p = Person("Alice") # 调用 __init__

2. __str____repr__:控制对象的字符串表示

  • __str__ 用于 str(obj)print(obj),面向用户。
  • __repr__ 用于调试,面向开发者,通常返回可执行的代码字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __str__(self):
return f"Point({self.x}, {self.y})"

def __repr__(self):
return f"Point(x={self.x}, y={self.y})"

p = Point(1, 2)
print(p) # Point(1, 2) ← 调用 __str__
print(repr(p)) # Point(x=1, y=2) ← 调用 __repr__

3. __len__:支持 len(obj)

1
2
3
4
5
6
7
8
9
class MyList:
def __init__(self, items):
self.items = items

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

my_list = MyList([1, 2, 3])
print(len(my_list)) # 3

4. __getitem__ / __setitem__:支持 obj[key]obj[key] = value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Vector:
def __init__(self, data):
self.data = data

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

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

v = Vector([10, 20, 30])
print(v[1]) # 20
v[1] = 99
print(v[1]) # 99

5. __add__:支持 + 运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)

def __repr__(self):
return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)

6. __eq__:支持 == 比较

1
2
3
4
5
6
7
8
9
10
class Book:
def __init__(self, title):
self.title = title

def __eq__(self, other):
return self.title == other.title

b1 = Book("Python")
b2 = Book("Python")
print(b1 == b2) # True

7. __call__:让对象像函数一样被调用

1
2
3
4
5
6
7
8
9
class Multiplier:
def __init__(self, factor):
self.factor = factor

def __call__(self, x):
return x * self.factor

double = Multiplier(2)
print(double(5)) # 10

参考资料

【Python 特性】魔法方法:让你的类和原生类一样顺滑_哔哩哔哩_bilibili