在Python中用我的类的实例划分数字

Luc*_*iot 24 python math division

我有一个叫做的类Time,我需要实现一个Frequency类.如何通过实例来实现划分ints或floats Time来获取实例Frequency

我已经知道__div__,__truediv__,__floordiv__和其他的Python特殊方法,我已经使用他们在我的代码用数字或其他类的实例来划分的类的实例,但我不能找到一种方法,通过我的类的实例来划分的数字.

是否可以通过Python中的类实例来划分数字?

Rig*_*leg 28

这个__rtruediv__方法就是你要找的.当x / y被执行时,如果type(x)不实现__div__(self, other)其中,方法other可以是类的type(y),然后type(y).__rtruediv__(y, x)被执行,并返回其结果.

用法:

class Foo:
    def __init__(self, x):
        self.x = x

    def __truediv__(self, other):
        return self.x / other

    def __rtruediv__(self, other):
        return other / self.x
Run Code Online (Sandbox Code Playgroud)
>>> f = Foo(10)    
>>> f / 10
1.0
>>> 10 / f
1.0
Run Code Online (Sandbox Code Playgroud)


Håk*_*Lid 9

是.您只需确保在收到浮点数或整数时Time.__rtruediv__()返回Frequency实例.

用法:

>>> 100 / Time(2)
Frequency(50.0)
>>> 2.5 / Time(5)
Frequency(0.5)
Run Code Online (Sandbox Code Playgroud)

执行:

class Time:
  def __init__(self, value):
    self.value = value

  def __rtruediv__(self, other):
    if not isinstance(other, (int, float)):
      return NotImplemented
    return Frequency(other / self.value)

class Frequency:
  def __init__(self, value):
    self.value = value

  def __repr__(self):
    return '{}({})'.format(self.__class__.__name__, self.value)
Run Code Online (Sandbox Code Playgroud)

python docs包含一个关于实现自定义类的算术运算的完整示例.

处理不兼容类型的正确方法是返回特殊值NotImplemented.

未实现

这应该由二进制特殊的方法被返回(如特殊的值__eq__(),__lt__(),__add__(),__rsub__(),等等),以指示该操作不相对于实施向其他类型

假设您尝试使用不受支持的复数,返回NotImplemented最终会导致TypeError出现正确的错误消息.(至少在python 3中)

>>> 100j / Time(2)

Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'complex' and 'Time'
Run Code Online (Sandbox Code Playgroud)