Python的魔术方法
一组特殊的方法,它们以双下划线(__)开头和结尾
允许我们在类中定义特定的行为,以便在对象上执行常见的操作
常见的魔术方法
__init__
: 初始化方法,在创建对象时调用。__str__
: 返回对象的字符串表示形式。__len__
: 返回对象的长度。__getitem__
: 获取对象的索引值。__add__
: 定义对象相加的行为。__sub__
: 定义对象相减的行为。__iter__
和__next__
: 定义可迭代对象和迭代器。__call__
: 将对象作为函数调用。__eq__
和__ne__
: 定义对象的相等和不相等比较。__lt__
,__gt__
,__le__
,__ge__
: 定义对象的小于、大于、小于等于和大于等于比较。__contains__
: 定义对象是否包含某个元素。
示例代码
__init__
: 初始化方法,在创建对象时调用。
class MyClass:
def __init__(self, name):
self.name = name
obj = MyClass("Alice")
print(obj.name) # 输出: Alice
__str__
: 返回对象的字符串表示形式。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(2, 3)
print(p) # 输出: (2, 3)
__len__
: 返回对象的长度。
class MyList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_list = MyList([1, 2, 3, 4, 5])
print(len(my_list)) # 输出: 5
__getitem__
: 获取对象的索引值。
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
my_list = MyList([1, 2, 3, 4, 5])
print(my_list[2]) # 输出: 3
__add__
: 定义对象相加的行为。
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)
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(f"({v3.x}, {v3.y})") # 输出: (6, 8)
__sub__
: 定义对象相减的行为。
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
v1 = Vector(5, 7)
v2 = Vector(2, 3)
v3 = v1 - v2
print(f"({v3.x}, {v3.y})") # 输出: (3, 4)
__iter__
和__next__
: 定义可迭代对象和迭代器。
class MyRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start >= self.end:
raise StopIteration
current = self.start
self.start += 1
return current
my_range = MyRange(1, 5)
for num in my_range:
print(num) # 输出: 1 2 3 4
__call__
: 将对象作为函数调用。
class Adder:
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
add_5 = Adder(5)
result = add_5(3)
print(result) # 输出: 8
__eq__
和__ne__
: 定义对象的相等和不相等比较。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __ne__(self, other):
return not self.__eq__(other)
person1 = Person("Alice", 25)
person2 = Person("Alice", 25)
person3 = Person("Bob", 30)
print(person1 == person2) # 输出: True
print(person1 != person3) # 输出: True
__lt__
,__gt__
,__le__
,__ge__
: 定义对象的小于、大于、小于等于和大于等于比较。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __lt__(self, other):
return self.width * self.height < other.width * other.height
def __gt__(self, other):
return self.width * self.height > other.width * other.height
def __le__(self, other):
return self.width * self.height <= other.width * other.height
def __ge__(self, other):
return self.width * self.height >= other.width * other.height
rect1 = Rectangle(4, 5)
rect2 = Rectangle(3, 6)
rect3 = Rectangle(2, 8)
print(rect1 < rect2) # 输出: False
print(rect1 > rect2) # 输出: True
print(rect1 <= rect3) # 输出: True
print(rect1 >= rect3) # 输出: False
__contains__
: 定义对象是否包含某个元素。
class MyList:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list) # 输出: True
print(6 in my_list) # 输出: False
其他常见魔术方法
__repr__
: 返回对象的可打印字符串表示形式。通常用于调试和日志记录。__enter__
和__exit__
: 用于定义上下文管理器,用于在进入和退出上下文时执行特定的操作,如资源的获取和释放。__setattr__
和__getattr__
: 用于设置和获取对象的属性。当属性被设置或获取时,这些方法会被调用。__del__
: 在对象被销毁时调用,用于执行一些清理操作。
举例
__repr__
: 返回对象的可打印字符串表示形式。通常用于调试和日志记录。
class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"MyClass({self.value})"
obj = MyClass(10)
print(obj) # 输出:MyClass(10)
__enter__
和__exit__
: 用于定义上下文管理器,用于在进入和退出上下文时执行特定的操作,如资源的获取和释放。
class MyContextManager:
def __enter__(self):
print("进入上下文")
def __exit__(self, exc_type, exc_value, traceback):
print("退出上下文")
with MyContextManager():
print("在上下文中执行操作")
输出:
进入上下文
在上下文中执行操作
退出上下文
__setattr__
和__getattr__
: 用于设置和获取对象的属性。当属性被设置或获取时,这些方法会被调用。
class MyClass:
def __setattr__(self, name, value):
print(f"设置属性 {name} = {value}")
super().__setattr__(name, value)
def __getattr__(self, name):
print(f"获取属性 {name}")
return None
obj = MyClass()
obj.attribute = 10 # 输出:设置属性 attribute = 10
print(obj.attribute) # 输出:获取属性 attribute,然后返回 None
__del__
: 在对象被销毁时调用,用于执行一些清理操作。
class MyClass:
def __del__(self):
print("对象被销毁")
obj = MyClass()
del obj # 输出:对象被销毁