Python的__div__()函数使用方法

1,208 阅读1分钟

在Python 2中,Python__div__() 魔法覆盖了自定义对象的除法操作。

在Python 3中,它被a / b__truediv__()__floordiv__()dunder方法所取代,而a // b

  • Python的__truediv__()方法被调用来实现正常的除法操作/ ,称为真除法。例如,为了评估表达式x / y ,Python试图调用x.__truediv__(y)
  • Python__floordiv__()方法实现了整数除法运算// ,称为地板除法。例如,要评估表达式x // y ,Python试图调用x.__floordiv__(y)

如果该方法没有实现,Python首先会尝试调用 [__rtruediv__](https://blog.finxter.com/python-__rtruediv__-magic-method/)[__rfloordiv__](https://blog.finxter.com/python-__rfloordiv__-magic-method/)在右边的操作数上,如果这也没有实现,它会引发一个TypeError

TypeError: /的操作数类型不支持。

在下面的例子中,你试图通过使用__div__() 魔术方法来覆盖自定义对象Data上的除法运算。

# Python 3 - WRONG:
class Data:
    def __div__(self, other):
        return 42.42


x = Data()
y = Data()

print(x / y)


然而,这对Python 3不起作用,你得到了下面的输出错误信息。

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 9, in <module>
    print(x / y)
TypeError: unsupported operand type(s) for /: 'Data' and 'Data'

为了解决这个问题,覆盖Python 3的__truediv__() 魔法,而不是Python 2的__div__() 魔法来定义真正的除法运算符x / y

你可以在下面的代码例子中看到它是如何实现的 (见高亮的行)。

class Data:
    def __truediv__(self, other):
        return 42.42


x = Data()
y = Data()

print(x / y)
# 42.42