Python魔术方法常用案例
一、构造与初始化方法
1. __init__ - 初始化方法
作用:对象创建后初始化属性
示例:
1 2 3 4 5 6 7
| class Person: def __init__(self, name, age): self.name = name self.age = age
p = Person("Alice", 30) print(p.name)
|
2. __new__ - 实例创建方法
作用:控制对象创建过程,常用于单例模式
示例:
1 2 3 4 5 6 7 8 9 10
| class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
s1 = Singleton() s2 = Singleton() print(s1 is s2)
|
二、字符串表示方法
1. __str__ - 友好字符串表示
作用:返回用户友好的字符串,用于str()和print()
示例:
1 2 3 4 5 6 7 8
| class Person: def __init__(self, name): self.name = name def __str__(self): return f"Person(name={self.name})"
p = Person("Bob") print(p)
|
2. __repr__ - 官方字符串表示
作用:返回开发者友好的字符串,用于repr()和调试
示例:
1 2 3 4 5 6 7 8 9
| class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})"
p = Point(3, 4) print(repr(p))
|
三、算术运算方法
1. __add__ - 加法运算
作用:定义对象的加法操作
示例:
1 2 3 4 5 6 7 8 9 10 11
| 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(v3.x, v3.y)
|
2. __sub__ - 减法运算
作用:定义对象的减法操作
示例:
1 2 3 4
| class Vector: def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y)
|
四、比较运算方法
1. __eq__ - 相等比较
作用:定义==运算符的行为
示例:
1 2 3 4 5 6 7 8 9
| class Student: def __init__(self, id): self.id = id def __eq__(self, other): return self.id == other.id
s1 = Student(1001) s2 = Student(1001) print(s1 == s2)
|
2. __lt__ - 小于比较
作用:定义<运算符的行为
示例:
1 2 3 4 5 6 7 8 9
| class Product: def __init__(self, price): self.price = price def __lt__(self, other): return self.price < other.price
p1 = Product(29.99) p2 = Product(39.99) print(p1 < p2)
|
五、容器相关方法
1. __len__ - 长度获取
作用:定义len()函数的行为
示例:
1 2 3 4 5 6 7 8
| class MyList: def __init__(self, items): self.items = items def __len__(self): return len(self.items)
ml = MyList([1, 2, 3, 4]) print(len(ml))
|
2. __getitem__ - 索引访问
作用:定义通过[]访问元素的行为
示例:
1 2 3 4 5 6 7
| class MyList: def __getitem__(self, index): return self.items[index]
ml = MyList([10, 20, 30]) print(ml[1])
|
六、其他常用方法
1. __call__ - 对象调用
作用:使对象可以像函数一样被调用
示例:
1 2 3 4 5 6
| class Calculator: def __call__(self, a, b): return a + b
calc = Calculator() print(calc(3, 5))
|
2. __enter__ 和 __exit__ - 上下文管理
作用:定义with语句的行为
示例:
1 2 3 4 5 6 7 8 9 10
| class FileHandler: def __init__(self, filename, mode): self.file = open(filename, mode) def __enter__(self): return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close()
with FileHandler("test.txt", "w") as f: f.write("Hello World")
|