Python运算符重载详解及实例代码

Python运算符重载详解及实例代码
最新回答
心碎比心死更痛

2026-10-20 14:38:29

Python运算符重载详解及实例代码

Python运算符重载是通过重写内置的魔法方法(以双下划线开头和结尾的方法)来实现的,这使得自定义类能够像内置类型一样使用运算符。以下是详细的解释和实例代码:

1. 构造函数和析构函数
  • __init__:构造函数,在对象创建时调用。
  • __del__:析构函数,在对象被回收时调用。
class Human: def __init__(self, n): self.name = n print("__init__", self.name) def __del__(self): print("__del__")h = Human('Tim') # 输出: __init__ Timh = 'a' # 输出: __del__2. 加减运算
  • __add__:重载加法运算符 +。
  • __sub__:重载减法运算符 -。
class Computation: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other def __sub__(self, other): return self.value - otherc = Computation(5)print(c + 5) # 输出: 10print(c - 3) # 输出: 23. 对象的字符串表达形式
  • __str__:用于 print() 和 str() 方法。
  • __repr__:用于 repr() 方法,优先于 __str__ 调用。
class Str: def __str__(self): return "__str__ called" def __repr__(self): return "__repr__ called"s = Str()print(s) # 输出: __str__ calledprint(repr(s)) # 输出: __repr__ calledprint(str(s)) # 输出: __str__ called4. 索引取值和赋值
  • __getitem__:重载索引取值操作 X[i]。
  • __setitem__:重载索引赋值操作 X[i] = v。
class Indexer: data = [1, 2, 3, 4, 5, 6] def __getitem__(self, index): return self.data[index] def __setitem__(self, k, v): self.data[k] = v print(self.data)i = Indexer()print(i[0]) # 输出: 1print(i[1:4]) # 输出: [2, 3, 4]i[0] = 10 # 输出: [10, 2, 3, 4, 5, 6]5. 设置和访问属性
  • __getattr__:在访问不存在的属性时调用。
  • __setattr__:在设置属性时调用。
class A: def __init__(self, ax, bx): self.a = ax self.b = bx def f(self): print(self.__dict__) def __getattr__(self, name): print("__getattr__") def __setattr__(self, name, value): print("__setattr__") self.__dict__[name] = valuea = A(1, 2)a.f() # 输出: {'a': 1, 'b': 2}a.x # 输出: __getattr__a.x = 3 # 输出: __setattr__a.f() # 输出: {'a': 1, 'x': 3, 'b': 2}6. 迭代器对象
  • __iter__:返回一个迭代器对象。
  • __next__:返回下一个迭代值。
class Next: def __init__(self, data=1): self.data = data def __iter__(self): return self def __next__(self): print("__next__ called") if self.data > 5: raise StopIteration else: self.data += 1 return self.datafor i in Next(3): print(i)print("-----------")n = Next(3)i = iter(n)while True: try: print(next(i)) except Exception as e: break

输出:

__next__ called4__next__ called5__next__ called6__next__ called-----------__next__ called4__next__ called5__next__ called6__next__ called

通过重载这些魔法方法,可以使自定义类的对象行为与内置对象一致,增强代码的灵活性和可读性。