Python中的魔法方法

Python中的魔法方法

本文将讲解Python中的魔法方法。

YouTube Video

Python中的魔法方法

Python中的魔法方法(特殊方法)是被特殊命名的方法,用于为类赋予独特的行为。例如,这些方法以双下划线(dunder)包围,如__init____str__。因此,它们也被称为dunder方法。

通过定义魔法方法,你可以定制类的标准行为。例如,定义__add__可以改变+运算符的行为。

初始化和字符串表示用的魔法方法

__init__:初始化方法

__init__方法是在实例创建时自动调用的构造函数。

1class Person:
2    def __init__(self, name, age):
3        self.name = name
4        self.age = age
5
6person = Person("Alice", 30)
7print(person.name)  # Alice

__str__:可读性字符串表示

__str__方法返回一个适合人类阅读的字符串表示。它会被print()str()调用。

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __str__(self):
6        return f"Person: {self.name}"
7
8person = Person("Bob")
9print(person)  # Person: Bob

__repr__:调试用字符串表示

__repr__方法返回一个用于调试的字符串表示。它会被repr()以及在解释器中显示对象时调用。

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __repr__(self):
6        return f"Person(name={self.name!r})"
7
8person = Person("Eve")
9print(repr(person))  # Person(name='Eve')

重载算术运算符

__add__+运算符

通过使用魔法方法,可以重载算术运算符。例如,__add__方法允许对+运算符进行重载。

 1class Vector:
 2    def __init__(self, x, y):
 3        self.x = x
 4        self.y = y
 5
 6    def __add__(self, other):
 7        return Vector(self.x + other.x, self.y + other.y)
 8
 9    def __repr__(self):
10        return f"Vector({self.x}, {self.y})"
11
12    # Other arithmetic magic methods:
13    # def __sub__(self, other):       # Subtraction (-)
14    # def __mul__(self, other):       # Multiplication (*)
15    # def __truediv__(self, other):   # True division (/)
16    # def __floordiv__(self, other):  # Floor division (//)
17    # def __mod__(self, other):       # Modulo (%)
18    # def __pow__(self, other):       # Exponentiation (**)
19
20v1 = Vector(1, 2)
21v2 = Vector(3, 4)
22print(v1 + v2)  # Vector(4, 6)

其他算术类魔法方法包括:。

方法 运算符
__add__ +
__sub__ -
__mul__ *
__truediv__ /
__floordiv__ //
__mod__ %
__pow__ **

定制比较运算符

你也可以重载比较运算符。例如,__eq__方法重载了相等运算符。

 1class Box:
 2    def __init__(self, volume):
 3        self.volume = volume
 4
 5    def __eq__(self, other):
 6        return self.volume == other.volume
 7
 8    def __lt__(self, other):
 9        return self.volume < other.volume
10
11    # Comparison magic methods:
12    # def __eq__(self, other):  # Equal to (==)
13    # def __ne__(self, other):  # Not equal to (!=)
14    # def __lt__(self, other):  # Less than (<)
15    # def __le__(self, other):  # Less than or equal to (<=)
16    # def __gt__(self, other):  # Greater than (>)
17    # def __ge__(self, other):  # Greater than or equal to (>=)
18
19b1 = Box(100)
20b2 = Box(200)
21
22print(b1 == b2)  # False
23print(b1 < b2)   # True

还有以下魔法方法:。这些魔法方法定义了对象间的相等和顺序等比较关系。

运算符 魔法方法
== __eq__
!= __ne__
< __lt__
<= __le__
> __gt__
>= __ge__

容器类型的魔法方法

你可以创建行为类似于列表或字典的类。

__len__:获取元素个数

__len__方法是一个返回元素个数的魔法方法。

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __len__(self):
6        return len(self.items)
7
8basket = Basket(["apple", "banana"])
9print(len(basket))  # 2

__getitem__:索引访问

__getitem__方法在进行索引访问时被调用。

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __getitem__(self, index):
6        return self.items[index]
7
8basket = Basket(["apple", "banana"])
9print(basket[1])  # banana

__setitem____delitem__:写入和删除

__setitem____delitem__方法在写入或删除元素时被调用。

 1class Basket:
 2    def __init__(self, items):
 3        self.items = items
 4
 5    def __setitem__(self, index, value):
 6        self.items[index] = value
 7
 8    def __delitem__(self, index):
 9        del self.items[index]
10
11basket = Basket(["apple", "banana"])
12basket[1] = "grape"
13del basket[0]
14print(basket.items)  # ['grape']

可迭代对象的魔法方法

要让对象能在for循环中可迭代,需要实现如下方法:。

__iter____next__

 1class Counter:
 2    def __init__(self, limit):
 3        self.limit = limit
 4        self.current = 0
 5
 6    def __iter__(self):
 7        return self
 8
 9    def __next__(self):
10        if self.current >= self.limit:
11            raise StopIteration
12        self.current += 1
13        return self.current
14
15for num in Counter(3):
16    print(num)
17# Output:
18# 1
19# 2
20# 3

上下文管理器(with语句)

通过定义__enter____exit__方法,可以实现with语句的前后处理。

 1class FileOpener:
 2    def __init__(self, filename):
 3        self.filename = filename
 4
 5    def __enter__(self):
 6        self.file = open(self.filename, 'r')
 7        return self.file
 8
 9    def __exit__(self, exc_type, exc_val, exc_tb):
10        self.file.close()
11
12with FileOpener("example.txt") as f:
13    content = f.read()
14    print(content)

可调用对象:__call__

通过定义__call__方法,可以使实例像函数一样被调用。

1class Greeter:
2    def __init__(self, greeting):
3        self.greeting = greeting
4
5    def __call__(self, name):
6        return f"{self.greeting}, {name}!"
7
8hello = Greeter("Hello")
9print(hello("Alice"))  # Hello, Alice!

总结

Python中的魔法方法是一种为类添加自然且直观行为的强大方式。每个魔法方法都有其明确的用途,合理实现可以编写出更灵活、更符合Python风格的代码。

魔法方法是支持Python对象在幕后交互和行为的“隐形接口”。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video