胶水Python

Py2-Py3区别: 除法的重载

2019-02-02  本文已影响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中, 运算符重载有以下:

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

官方: Python3运算符

上一篇 下一篇

猜你喜欢

热点阅读