Python入门——类与对象:运算

文章目录

    • 1. 算术运算
    • 2. 反运算
    • 3. 一元操作符

以下内容来自于网课学习笔记。

使用的环境:

  • Window10+64位操作系统
  • PyCharm+Python3.7

1. 算术运算

Python入门——类与对象:运算_第1张图片

class New_int(int):
    def __add__(self, other):
        return int.__add__(self,other)
    def __sub__(self, other):
        return int.__sub__(self,other)
a=New_int(3)
b=New_int(6)
print(a-b)
print(a+b)

2. 反运算

Python入门——类与对象:运算_第2张图片

class N_int(int):
    def __radd__(self, other):
        return int.__add__(self,other)
    def __rsub__(self, other):
        return int.__sub__(self,other)

a=N_int(3)
b=N_int(6)
# 正常运算
print(a-b)        # ————> -3
print(a+b)        # ————> 9
c=N_int(5)
# 执行了反运算 c-3=5-3=2
print(3-c)        # ————> 2

调整参数顺序:

class N_int(int):
    def __rsub__(self, other):
        return int.__sub__(other,self)

a=N_int(3)
b=N_int(6)
print(a-b)        # ————> -3
print(a+b)        # ————> 9
c=N_int(5)
# 反运算 c-3=5-3=2
print(3-c)        # ————> -2

3. 一元操作符

Python入门——类与对象:运算_第3张图片

你可能感兴趣的:(#,Python基础语法)