原文链接:https://www.jb51.net/article/86988.htm

这篇文章主要介绍了Python中的数学运算操作符使用进阶,也包括运算赋值操作符等基本知识的小结

Python中对象的行为是由它的类型 (Type) 决定的。所谓类型就是支持某些特定的操作。数字对象在任何编程语言中都是基础元素,支持加、减、乘、除等数学操作。
Python的数字对象有整数和浮点数,支持各种数学操作,比如+, -,*, /等。 没有这些操作符,程序中只能使用函数调用的方式进行数学运算,比如add(2, 3), sub(5, 2)。
程序中操作符的作用与普通数学操作的用法是一致的,使用中更加简便直观。Python中,这些操作符实现是通过定义一些object的特殊方法实现的,比如object.__add__()和object.__sub__()。如果用户在自己定义类时实现上述特殊方法,可以使自定义类的对象支持相应的数学操作,从而模拟数字对象的行为。这其实是达到了操作符重载的效果。

这里通过实现一个具有支持加法运算的中文数字类说明如何在Python中实现一个支持常见的数学操作。ChineseNumber类的基本定义如下。

1

2

3

4

5

6

7

8

9

10

11

12

class ChineseNumber:

  def __init__(self, n):

    self.num = n

    self.alphabet = [u'零', u'一', u'二', u'三', u'四',

      u'五', u'六', u'七', u'八', u'九', u'十']

  def __str__(self):

    sign = '负' if self.num < 0 else ''

    return sign + ''.join([self.alphabet[int(s)] for s in str(abs(self.num))])

  def __repr__(self):

    return self.__str__()

目前,实现的效果是这样的:

1

2

3

4

5

6

>>> a = ChineseNumber(2)

>>> a  #调用a.__repr__()

>>> print(a)  #调用a.__str__()

一般数学操作符
定义类时,实现__add__()方法,可以给这个类增加+操作符。给ChineseNumber增加如下方法:

1

2

3

4

5

6

7

def __add__(self, other):

  if type(other) is ChineseNumber:

    return ChineseNumber(self.num + other.num)

  elif type(other) is int:

    return ChineseNumber(self.num + other)

  else:

    return NotImplemented

这时ChineseNumber的对象就可以使用+了。

1

2

3

4

5

6

7

>>> a, b = ChineseNumber(2), ChineseNumber(10)

>>> a + b

十二

>>> a + 5

>>> a + 3.7

TypeError: unsupported operand type(s) for +: 'ChineseNumber' and 'float'

对于+,a + b相当于调用a.__add__(b). 类似地,可以定义其他数学操作符,见下表。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

object.__add__(self, other): +

object.__sub__(self, other): -

object.__mul__(self, other): *

object.__matmul__(self, other): @

object.__truediv__(self, other): /

object.__floordiv__(self, other): //

object.__mod__(self, other): %

object.__divmod__(self, other): divmod, divmod(a, b) = (a/b, a%b)

object.__pow__(self, other[,modulo]): **, pow()

object.__lshift__(self, other): <<

object.__rshift__(self, other): >>

object.__and__(self, other): &

object.__xor__(self, other): ^

object.__or__(self, other): |

操作数反转的数学操作符 (Reflected/Swapped Operand)

1

2

>>> 2 + a

TypeError: unsupported operand type(s) for +: 'int' and 'ChineseNumber'

2是整数类型,它的__add__()方法不支持ChineseNumber类的对象,所以出现了上述错误。定义操作数反转的数学操作符可以解决这个问题。给ChineseNumber类添加__radd__()方法,实现操作数反转的+运算。

1

2

def __radd__(self, other):

  return self.__add__(other)

对于a + b,如果a没有定义__add__()方法,Python尝试调用b的__radd__()方法。此时,a + b相当于调用b.__radd__(a)。

1

2

3

>>> a = ChineseNumber(2)

>>> 2 + a

类似地,可以定义其他操作数反转的数学操作符,见下表。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

object.__radd__(self, other): +

object.__rsub__(self, other): -

object.__rmul__(self, other): *

object.__rmatmul__(self, other): @

object.__rtruediv__(self, other): /

object.__rfloordiv__(self, other): //

object.__rmod__(self, other): %

object.__rdivmod__(self, other): divmod, divmod(a, b) = (b/a, b%a)

object.__rpow__(self, other[,modulo]): **, pow()

object.__rlshift__(self, other): <<

object.__rrshift__(self, other): >>

object.__rand__(self, other): &

object.__rxor__(self, other): ^

object.__ror__(self, other): |

运算赋值操作符
运算赋值操作符使用单个操作符完成运算和赋值操作,比如a += b相当于调用a = a + b。为ChineseNumber增加__iadd__()方法,可以实现+=操作符。

1

2

3

4

5

6

7

8

9

def __iadd__(self, other):

  if type(other) is ChineseNumber:

    self.num += other.num

    return self

  elif type(other) is int:

    self.num += other

    return self

  else:

    return NotImplemented

此时,

1

2

3

4

5

6

7

>>> a, b = ChineseNumber(2), ChineseNumber(10)

>>> a += b

>>> a

十二

>>> a + 7

>>> a

十九

类似地,可以定义其他运算赋值操作符,见下表。

1

2

3

4

5

6

7

8

9

10

11

12

13

object.__iadd__(self, other): +=

object.__isub__(self, other): -=

object.__imul__(self, other): *=

object.__imatmul__(self, other): @=

object.__itruediv__(self, other): /=

object.__ifloordiv__(self, other): //=

object.__imod__(self, other): %=

object.__ipow__(self, other[,modulo]): **=

object.__ilshift__(self, other): <<=

object.__irshift__(self, other): >>=

object.__iand__(self, other): &=

object.__ixor__(self, other): ^=

object.__ior__(self, other): |=

一元数学操作符
一元数学操作符是只有一个操作数的运算,比如取负数的操作符-。-对应的特殊函数是__neg__()。为ChineseNumber添加__neg__()方法,

1

2

def __neg__(self):

  return ChineseNumber(-self.num)

此时,ChineseNumber对象就支持-操作了。

1

2

3

>>> a = ChineseNumber(5)

>>> -a

负五

其他一元运算符见下表。

1

2

3

4

5

6

7

8

9

object.__neg__(self): -

object.__pos__(self): +

object.__abs__(self): abs()

object.__invert__(self): ~

object.__complex__(self): complex()

object.__int__(self): int()

object.__float__(self): float()

object.__round__(self): round()

object.__index__(self): operator.index()

运算操作符使用进阶,也包括运算赋值操作符等基本知识的小结

Python中的数学运算操作符使用进阶相关推荐

  1. python中mod运算符_Python中的数学运算操作符使用进阶

    Python中对象的行为是由它的类型 (Type) 决定的.所谓类型就是支持某些特定的操作.数字对象在任何编程语言中都是基础元素,支持加.减.乘.除等数学操作. Python的数字对象有整数和浮点数, ...

  2. 捋一捋Python中的数学运算math库(上篇)

    正式的Python专栏第18篇,同学站住,别错过这个从0开始的文章! 很多学习编程的都多多少少学习了一些数学知识. 学委之前也简单吐槽了 Python中奇葩的round函数! 这篇我们讲讲那些常用的数 ...

  3. [转载] Python中的数学函数,三角函数,随机数函数

    参考链接: Python中的数学math函数 3(三角函数和角函数) 数学函数 函数返回值 ( 描述 )abs(x)返回数字的绝对值,如abs(-10) 返回 10ceil(x)返回数字的上入整数,如 ...

  4. linux shell数学计算器,技术|使用 GNU bc 在 Linux Shell 中进行数学运算

    在 shell 中使用 bc 更好地做算数,它是一种用于高级计算的数学语言. 大多数 POSIX 系统带有 GNU bc,这是一种任意精度的数字处理语言.它的语法类似于 C,但是它也支持交互式执行语句 ...

  5. linux中bc用法英文,使用GNU bc在Linux Shell中进行数学运算

    在 shell 中使用 bc 更好地做算数,它是一种用于高级计算的数学语言. 大多数 POSIX 系统带有 GNU bc,这是一种任意精度的数字处理语言.它的语法类似于 C,但是它也支持交互式执行语句 ...

  6. 【Python】Python中内置的%操作符

    Python中内置的%操作符可用于格式化字符串操作,控制字符串的呈现格式.Python中还有其他的格式化字符串的方式,但%操作符的使用是最方便的. 格式符为真实值预留位置,并控制显示的格式.格式符可以 ...

  7. Python中的方根运算及对数运算公式

    Python中的方根运算及对数运算公式 在Python中,我们可以使用math模块来进行方根及对数运算.下面是一些常用的代码示例: 计算平方根 使用math.sqrt(x)函数可以计算一个数的平方根. ...

  8. Microsoft Excel 教程:如何在 Excel 中进行数学运算?

    欢迎观看 Microsoft Excel 教程,小编带大家学习 Microsoft Excel 的使用技巧,了解如何在 Excel 中进行数学运算,而不是使用计算器.可以输入简单的公式来对两个或多个数 ...

  9. Python中列表常用的操作符

    下面介绍Python中列表的常用操作符 1.比较操作符:>.<.==.注意,列表比较大小的时候是从第一个元素开始比较,而不看列表长度,返回True或者False 2.逻辑操作符:and.o ...

最新文章

  1. Maven 的这 7 个问题你思考过没有?
  2. 百练OJ:2810:完美立方
  3. 【实战篇】| 小鹿教你用动态规划撩妹的正确方式
  4. L - Who is the Champion
  5. 怎么用计算机改变声音的音调,调音台使用教程大全
  6. 基础知识—数据类型-常量及符号
  7. Netty工作笔记0017---Channel和Buffer梳理
  8. [转]jQuery为控件添加水印文字
  9. 地图染色(四色定理)问题
  10. 中国传统的节日(端午节)
  11. EfficientNet迁移学习(四) —— 损失函数解析
  12. 运动无线耳机哪个品牌比较好、口碑最好的运动蓝牙耳机
  13. HTB靶场系列 linux靶机 Sense靶机
  14. java/php/net/python驾校学员管理系统设计
  15. 企业级别的应用程序开发
  16. gregorian(格里高力)历转换公历
  17. 2022.3.1总结
  18. 元件封装知识(转载)
  19. js css如何按比例放大视频或者图片
  20. mini6410 USB下载线驱动

热门文章

  1. LP78070FSPF 三档小风扇 升压7.5V 无手电筒功能 双灯显示
  2. 经纬恒润AUTOSAR全面适配芯驰车规芯片,联合打造全场景国产解决方案
  3. ChinaSkills-网络系统管理(2022年全国职业院校技能大赛-模块C-网络构建-01卷-真题 )
  4. cuckoo沙箱的搭建
  5. 预则立,约则达,车检预约制,车检行业大趋势
  6. volatile unsigned int 什么意思
  7. 局域网 固定IP地址 静态IP 无法上网,设置方法
  8. html5 矢量图形插件,HTML5画布矢量图形?
  9. MongoDB多表查询各属性详解
  10. mysql创建表分区详细介绍及示例