Python 20个魔法函数
本文将为您详细介绍Python中的20个魔法函数,这些函数能够在代码中释放神奇的力量。让我们一起来了解这些特殊的函数,并提供一些在实际接口自动化工作中的示例代码。魔法函数(Magic Methods),也被称为特殊方法或双下划线方法,是Python中一些特殊命名的函数,它们以双下划线开头和结尾。这些函数定义了对象在特定情况下的行为,例如创建、比较、运算、迭代等。
以下是20个常用的魔法函数及其功能的详细解释和示例代码:
__init__(self[, args...]):对象初始化函数,在创建对象时调用。
class MyClass:def __init__(self, name):self.name = nameobj = MyClass("Alice")
__str__(self):返回对象的字符串表示。
class Point:def __init__(self, x, y):self.x = xself.y = ydef __str__(self):return f"({self.x}, {self.y})"p = Point(3, 4)print(p) # 输出: (3, 4)
__len__(self):返回对象的长度。
class MyList:def __init__(self, items):self.items = itemsdef __len__(self):return len(self.items)my_list = MyList([1, 2, 3, 4, 5])print(len(my_list)) # 输出: 5
__getitem__(self, key):获取对象的指定元素。
class MyList:def __init__(self, items):self.items = itemsdef __getitem__(self, index):return self.items[index]my_list = MyList([1, 2, 3, 4, 5])print(my_list[2]) # 输出: 3
__setitem__(self, key, value):设置对象的指定元素。
class MyList:def __init__(self, items):self.items = itemsdef __setitem__(self, index, value):self.items[index] = valuemy_list = MyList([1, 2, 3, 4, 5])my_list[2] = 10print(my_list.items) # 输出: [1, 2, 10, 4, 5]
__delitem__(self, key):删除对象的指定元素。
class MyList:def __init__(self, items):self.items = itemsdef __delitem__(self, index):del self.items[index]my_list = MyList([1, 2, 3, 4, 5])del my_list[2]print(my_list.items) # 输出: [1, 2, 4, 5]
__contains__(self, item):判断对象是否包含指定元素。
class MyList:def __init__(self, items):self.items = itemsdef __contains__(self, item):return item in self.itemsmy_list = MyList([1, 2, 3, 4, 5])print(3 in my_list) # 输出: True
__iter__(self):返回迭代器对象。
class MyList:def __init__(self, items):self.items = itemsdef __iter__(self):return iter(self.items)my_list = MyList([1, 2, 3, 4, 5])for item in my_list:print(item) # 依次输出: 1, 2, 3, 4, 5
__next__(self):返回迭代器的下一个元素。
class MyList:def __init__(self, items):self.items = itemsself.index = 0def __iter__(self):return selfdef __next__(self):if self.index >= len(self.items):raise StopIterationvalue = self.items[self.index]self.index += 1return valuemy_list = MyList([1, 2, 3, 4, 5])for item in my_list:print(item) # 依次输出: 1, 2, 3, 4, 5
__eq__(self, other):判断两个对象是否相等。
class Point:def __init__(self, x, y):self.x = xself.y = ydef __eq__(self, other):return self.x == other.x and self.y == other.yp1 = Point(3, 4)p2 = Point(3, 4)print(p1 == p2) # 输出: True
__lt__(self, other):判断一个对象是否小于另一个对象。
class Point:def __init__(self, x, y):self.x = xself.y = ydef __lt__(self, other):return self.x < other.x and self.y < other.yp1 = Point(2, 3)p2 = Point(3, 4)print(p1 < p2) # 输出: True
__gt__(self, other):判断一个对象是否大于另一个对象。
class Point:def __init__(self, x, y):self.x = xself.y = ydef __gt__(self, other):return self.x > other.x and self.y > other.yp1 = Point(3, 4)p2 = Point(2, 3)print(p1 > p2) # 输出: True
__add__(self, other):定义对象的加法操作。
class Vector:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):return Vector(self.x + other.x, self.y + other.y)v1 = Vector(1, 2)v2 = Vector(3, 4)result = v1 + v2print(f"({result.x}, {result.y})") # 输出: (4, 6)
__sub__(self, other):定义对象的减法操作。
class Vector:def __init__(self, x, y):self.x = xself.y = ydef __sub__(self, other):return Vector(self.x - other.x, self.y - other.y)v1 = Vector(3, 4)v2 = Vector(1, 2)result = v1 - v2print(f"({result.x}, {result.y})") # 输出: (2, 2)
__mul__(self, other):定义对象的乘法操作。
class Point:def __init__(self, x, y):self.x = xself.y = ydef __mul__(self, factor):return Point(self.x * factor, self.y * factor)p = Point(2, 3)result = p * 2print(f"({result.x}, {result.y})") # 输出: (4, 6)
__call__(self[, args...]):使对象可调用。
class Calculator:def __call__(self, a, b):return a + bcalc = Calculator()result = calc(3, 4)print(result) # 输出: 7
__enter__(self) 和 __exit__(self, exc_type, exc_value, traceback):定义上下文管理器。
class FileManager:def __init__(self, filename):self.filename = filenamedef __enter__(self):self.file = open(self.filename, 'r')return self.filedef __exit__(self, exc_type, exc_value, traceback):self.file.close()with FileManager("example.txt") as file:contents = file.read()print(contents)
__getattr__(self, name):在访问不存在的属性时调用。
class Person:def __getattr__(self, name):return f"Attribute '{name}' does not exist."p = Person()print(p.age) # 输出: Attribute 'age' does not exist.__setattr__(self, name, value):在设置属性值时调用。class Person:def __setattr__(self, name, value):print(f"Setting attribute '{name}' to '{value}'")super().__setattr__(name, value)p = Person()p.name = "Alice" # 输出: Setting attribute 'name' to 'Alice'
__delattr__(self, name):在删除属性时调用。
class Person:def __delattr__(self, name):print(f"Deleting attribute '{name}'")super().__delattr__(name)p = Person()del p.name # 输出: Deleting attribute 'name'

浙公网安备 33010602011771号