python 特殊方法和运算符重载

特殊方法和运算符重载

Python 的运输符实际上是通过调用对象的特殊方法实现的

a = 10
b = 10
c = a + b
d = a.__add__(b)
print('c=',c)
print('d=',d)

 特殊方法

方法 说明 例子
__init__ 构造方法 对象创建:p = Person()
__del__ 析构方法 对象回收
__call__ 函数调用 a()
__getattr__ 点号运算 a.xxx
__repr__,str__ 打印,转换 print(a)
__getitem__ 索引运算 a[key]

__setitem__

索引赋值

a[key]=value

__len__ 长度 len(a)

 运算符方法

运算符 特殊方法 说明
运算符 + __add__ 加法
运算符 - __sub__ 减法
<,<,=,== __lt__,__le__,__eq__ 比较运算符
>,> =,!= __gt__,__ge__,__ne__ 比较运算符
|,^,& __or__,__xor__,__and__ 或,异或,与
<<,>> __lshift__,__rshift__ 左移,右移
*,/,%,// __mul__,__truediv__,__mod__,__floordiv__ 乘,浮点数,模运算(取余),整数除
** __pow__ 指数运算

# 运算符的重载
class Student:
    def __init__(self,name):
        self.name = name
    

p1 = Student('小明')
p2 = Student('小红2')

x = p1 + p2
print(x)

# 运算符的重载
class Student:
    def __init__(self,name):
        self.name = name
    
    def __add__(self,other):
        if isinstance(other, Student):
            return "{0}--{1}".format(self.name,other.name)
        else:
            return "不是同类对象,不能相加"

p1 = Student('小明')
p2 = Student('小红2')

x = p1 + p2
print(x)

Guess you like

Origin blog.csdn.net/qq_26086231/article/details/121452148