Python Magic Methods: A Comprehensive Guide
This article introduces Python's magic methods, explaining their roles in object-oriented programming, including __init__, __str__, __len__, and more, with practical code examples and outputs.
前言
Python中的魔法方法(或称为特殊方法)是指那些名字以双下划线__开头和结尾的方法。这些方法定义了类的行为,使我们能够更加灵活地控制类的实例化过程、比较操作、运算符重载等。本文将介绍并展示10个常用的魔法方法。
1. __init__ 和 __new__
说明:
__init__ 是一个初始化方法,在创建新实例后立即被调用,用于设置初始状态。
__new__ 是一个构造器,负责创建实例本身。在__init__之前被调用,通常用于控制对象的创建过程,如单例模式。
示例代码:
class Person: def __init__(self, name, age): print("Initializing Person instance.") self.name = name self.age = age def __new__(cls, *args, **kwargs): print("Creating a new Person object.") return super().__new__(cls) p = Person("Alice", 30) print(p.name, p.age)输出结果:
Creating a new Person object. Initializing Person instance. Alice 302. __str__ 和 __repr__
说明:
__str__ 方法定义了一个类的“用户友好”字符串表示形式,通常用于打印和显示。
__repr__ 方法定义了类的“官方”字符串表示形式,主要用于调试和开发。
示例代码:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})" def __repr__(self): return f"Person('" + self.name + "', " + str(self.age) + ")" p = Person("Bob", 25) print(str(p)) print(repr(p))输出结果:
Person(name=Bob, age=25) Person('Bob', 25)3. __len__
说明:
__len__ 方法定义了类的实例的长度,通常用于序列类型。
示例代码:
class MyList: def __init__(self, elements): self.elements = elements def __len__(self): return len(self.elements) ml = MyList([1, 2, 3, 4]) print(len(ml))输出结果: 4 4. __getitem__ 和 __setitem__
说明:
__getitem__ 方法定义了索引获取操作的行为。
__setitem__ 方法定义了索引赋值操作的行为。
示例代码:
class MyList: def __init__(self, elements): self.elements = elements def __getitem__(self, index): return self.elements[index] def __setitem__(self, index, value): self.elements[index] = value ml = MyList([1, 2, 3, 4]) print(ml[1]) # Get item ml[1] = 10 # Set item print(ml[1])输出结果:
2 105. __delitem__
说明:
__delitem__ 方法定义了删除索引操作的行为。
示例代码:
class MyList: def __init__(self, elements): self.elements = elements def __delitem__(self, index): del self.elements[index] ml = MyList([1, 2, 3, 4]) print(ml.elements) del ml[1] print(ml.elements)输出结果:
[1, 2, 3, 4] [1, 3, 4]6. __iter__ 和 __next__
说明:
__iter__ 方法定义了迭代器对象的获取行为。
__next__ 方法定义了迭代器的下一个元素的获取行为。
示例代码:
class MyIterator: def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.data): raise StopIteration result = self.data[self.index] self.index += 1 return result mi = MyIterator([1, 2, 3, 4]) <span><span>for</span> item <span>in</span> <span>mi:</span></span><br><code> print(item)输出结果:
1 2 3 47. __eq__
说明:
__eq__ 方法定义了两个实例之间的等价性比较。
示例代码:
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y p1 = Point(1, 2) p2 = Point(1, 2) print(p1 == p2)输出结果: True 8. __lt__ 和 __gt__
说明:
__lt__ 方法定义了小于比较操作。
__gt__ 方法定义了大于比较操作。
示例代码:
class Point: def __init__(self, x, y): self.x = x self.y = y def __lt__(self, other): return (self.x, self.y) < (other.x, other.y) def __gt__(self, other): return (self.x, self.y) > (other.x, other.y) p1 = Point(1, 2) p2 = Point(3, 4) print(p1 < p2) print(p1 > p2)输出结果:
True False9. __add__
说明:
__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(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 print(v3.x, v3.y)输出结果: 4 6 10. __call__
说明:
__call__ 方法允许一个实例像函数一样被调用。
示例代码:
class Counter: def __init__(self): self.count = 0 def __call__(self): self.count += 1 return self.count counter = Counter() print(counter()) # First call print(counter()) # Second call输出结果:
1 2以上就是关于Python魔法方法的一些基本示例及其解释。这些魔法方法使得我们可以更灵活地定制Python类的行为,希望这些示例能够帮助您更好地理解和使用它们。
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
