【Python】Python魔术方法

介绍

Python 的**魔术方法(Magic Methods)**是以双下划线 __ 包围的特殊方法,常用于重载运算符、定义对象行为等。

对象的创建与销毁

方法 作用
__new-_(cls, *args, **kwargs) 创建对象(在__init__之前调用)
__init__(self, \*args, \*\*kwargs) 初始化对象
__del__(self) 对象销毁时调用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class MyClass:
    def __new__(cls):
        print("Creating instance")
        return super().__new__(cls)

    def __init__(self):
        print("Initializing instance")

    def __del__(self):
        print("Destroying instance")

obj = MyClass()
del obj  # 显式销毁对象

字符串表示

方法 作用
__str__(self) str(obj),用于用户可读的字符串表示
__repr__(self) repr(obj),用于调试的字符串表示
__format__(self, format_spec) format(obj, spec),自定义格式化
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Person:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Person: {self.name}"  # 用户友好的描述

    def __repr__(self):
        return f"Person(name={self.name!r})"  # 开发者友好的表示

p = Person("Alice")
print(str(p))   # Person: Alice
print(repr(p))  # Person(name='Alice')

算数运算符重载

方法 作用
__add__(self, other) + 加法
__sub__(self, other) - 减法
__mul__(self, other) * 乘法
__truediv__(self, other) / 除法
__floordiv__(self, other) // 整除
__mod__(self, other) % 取余
__pow__(self, other) ** 幂运算
__neg__(self) - 取负
__abs__(self) abs(obj) 绝对值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y

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

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

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

比较运算符

方法 作用
__eq__(self, other) == 等于
__ne__(self, other) != 不等于
__lt__(self, other) < 小于
__le__(self, other) <= 小于等于
__gt__(self, other) > 大于
__ge__(self, other) >= 大于等于
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Person:
    def __init__(self, age):
        self.age = age

    def __lt__(self, other):
        return self.age < other.age

p1 = Person(25)
p2 = Person(30)
print(p1 < p2)  # True

容器相关

方法 作用
__len__(self) len(obj),返回对象长度
__getitem__(self, key) obj[key],获取元素
__setitem__(self, key, value) obj[key] = value设置元素
__delitem__(self, key) del obj[key],删除元素
__contains__(self, item) item in obj检查是否包含
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class CustomList:
    def __init__(self, data):
        self.data = data

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

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

cl = CustomList([1, 2, 3])
print(len(cl))   # 3
print(cl[1])     # 2

迭代器

方法 作用
__iter__self) 使对象可迭代
__next__(self) next(obj)返回迭代器的下一个元素
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Counter:
    def __init__(self, max_count):
        self.max = max_count
        self.current = 0

    def __iter__(self):
        return self  # 迭代器返回自身

    def __next__(self):
        if self.current < self.max:
            self.current += 1
            return self.current
        else:
            raise StopIteration

c = Counter(3)
for i in c:
    print(i)  # 1, 2, 3

上下文管理(Context Manager)

方法 作用
__enter__(self) 进入 with 代码块
__exit__(self, exc_type, exc_value, traceback) 退出 with 代码块
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class FileHandler:
    def __init__(self, filename, mode):
        self.file = open(filename, mode)

    def __enter__(self):
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

with FileHandler("test.txt", "w") as f:
    f.write("Hello, world!")
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计