美文网首页胶水Python
Py2-Py3区别: 除法的重载

Py2-Py3区别: 除法的重载

作者: 爱折腾的大懒猪 | 来源:发表于2019-02-02 00:17 被阅读4次

今天在Biopython中使用 PDB.Vector的对象进行除法运算时, 报错:

TypeError: unsupported operand type(s) for /: 'Vector' and 'int'

经查, 原因是Python2 和Python3的区别.

对于除法/ 运算符的重载, Python2只是简单的__div__, 而Python3则是使用__truediv__.

因此, 为了代码日后能更好地兼容, 应该使用Python3的格式: __truediv__. 并在开头时引入未来特性.

from __future__ import division

class A(object):
  def __truediv__(self, other):
    pass

在Python3中, 运算符重载有以下:

  • __truediv__ : 除法 \ , Py2使用__div__. 除法运算3/2 == 1.5, Py2则3/2==1. 实际上, Py2.7.15里面是已经支持可以含有__truediv__, 针对浮点除法时. 如果要整数也使用, 则需要from __future__ import division
  • __floordiv__ : 除后向下取整(整除) \\. 如果使用浮点, 返回则是整数值大小的浮点数. 实际Py2支持该方法, 但默认下/已经是整除(针对int/int).
  • __add__ : 加法 +
  • __sub__ : 减法 -
  • __mul__ : 乘法 *
  • __pow__ : 乘方运算 **
  • __mod__ : 取模, %
  • __divmod__ : 调用divmod时行为, 返回(整数商, 余数): divmod(11,3) => (3,2)
  • __neg__ : 负数, 即-var.
  • __pos__ : 正数, 即+var.
  • __matmul__ 矩阵乘 a@b. Py3.5 新特性.

在上述方法前面加i, 对于的是自变操作符, 如__iadd__对应+=.

官方: Python3运算符

相关文章

网友评论

    本文标题:Py2-Py3区别: 除法的重载

    本文链接:https://www.haomeiwen.com/subject/orirsqtx.html