Python中的魔法方法(Magic Methods)或特殊方法,是指那些以双下划线(__
)开始和结束的方法。这些方法在Python中扮演着特殊角色,用于实现类的特殊功能或行为,如初始化对象、定义对象的字符串表示、实现运算符重载等。以下是一些常见的魔法方法及其示例:
1. __init__(self, [...])
- 作用:类的构造函数,用于在对象创建时初始化其状态。
- 示例:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book = Book("The Catcher in the Rye", "J.D. Salinger")
print(book.title) # 输出: The Catcher in the Rye
2. __str__(self)
- 作用:定义对象的字符串表示形式,当使用
print()
函数或str()
函数时会被调用。 - 示例:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("The Catcher in the Rye", "J.D. Salinger")
print(book) # 输出: The Catcher in the Rye by J.D. Salinger
3. __repr__(self)
- 作用:返回对象的官方字符串表示,主要用于开发者调试。
- 示例:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __repr__(self):
return f"Book(title={self.title!r}, author={self.author!r})"
book = Book("The Catcher in the Rye", "J.D. Salinger")
print(repr(book)) # 输出: Book(title='The Catcher in the Rye', author='J.D. Salinger')
4. __add__(self, other)
- 作用:定义对象间的加法操作,允许使用
+
运算符。 - 示例(假设我们有一个自定义的数值类型):
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(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x, v3.y) # 输出: 4 6
5. __call__(self, [...])
- 作用:使对象可以像函数一样被调用。
- 示例:
class Adder:
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
adder = Adder(5)
print(adder(3)) # 输出: 8
6. __len__(self)
- 作用:定义对象的长度,当使用
len()
函数时会被调用。 - 示例:
class MyList:
def __init__(self, *args):
self.items = list(args)
def __len__(self):
return len(self.items)
my_list = MyList(1, 2, 3)
print(len(my_list)) # 输出: 3
7. 其他魔法方法
Python中还有许多其他魔法方法,如__getitem__
、__setitem__
用于实现索引操作,__eq__
、__lt__
用于实现比较操作,__iter__
、__next__
用于实现迭代器协议等。这些魔法方法共同构成了Python中面向对象编程的强大功能。
综上所述,Python中的魔法方法是实现类特殊功能的关键,掌握它们对于深入理解Python的面向对象编程具有重要意义。