1 定义魔法函数是 Python 中以双下划线开头和结尾的特殊方法它们定义了类的行为让对象能够响应各种操作。2 字符串表示__init__ 初始化函数 __str__ 普通用户查看 __repr__ 开发人员查看class Person: def __init__(self, name, age): self.name name self.age age def __str__(self): return f{self.name} {self.age} def __repr__(self): return fPerson({self.name},{self.age})3 算术运算# 比较运算符 __gt__ __ge__ __lt__ __le__ __eq__ __ne__ ! # 算数运算符 __add__ __sub__ - __mul__ * __truediv__ / __floordiv__ // __mod__ % __divmod__ // % __pow__ **def __gt__(self, other): print(self, other) 重写 比较运算符 other就是带比较对象 return self.age other.age def __lt__(self, other): return self.age other.age def __ge__(self, other): return self.age other.age def __le__(self, other): return self.age other.age def __eq__(self, other): return self.age other.age def __ne__(self, other): return self.age ! other.age def __add__(self, other): return 888 def __sub__(self, other): return self.age - other.age def __mul__(self, other): return self.age * other.age def __truediv__(self, other): return self.age / other.age def __floordiv__(self, other): return self.age // other.age def __mod__(self, other): return self.age % other.age def __divmod__(self, other): return self.age // other.age, self.age % other.age def __pow__(self, other): return self.age ** other.age p1 Person(张三, 3) p2 Person(李四, 5)print(p1 p2) .... print(p1 ** p2) print(p2 ! p1)结果返回 True Flase