我有一個叫Time
的類,我需要實現一個Frequency
類。我如何實現將int
s或float
s分配給Time
的實例以獲得Frequency
的實例?用Python中我的類的實例劃分數字
我已經知道__div__
,__truediv__
,__floordiv__
和其他Python特殊方法,我已經使用他們在我的代碼用數字或其他類的實例來劃分的類的實例,但我不能找到一種方法來劃分數由我的班級的一個實例。
是否有可能實現用Python中的類的實例分隔數字?
我有一個叫Time
的類,我需要實現一個Frequency
類。我如何實現將int
s或float
s分配給Time
的實例以獲得Frequency
的實例?用Python中我的類的實例劃分數字
我已經知道__div__
,__truediv__
,__floordiv__
和其他Python特殊方法,我已經使用他們在我的代碼用數字或其他類的實例來劃分的類的實例,但我不能找到一種方法來劃分數由我的班級的一個實例。
是否有可能實現用Python中的類的實例分隔數字?
__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
>>> f = Foo(10)
>>> f/10
1.0
>>> 10/f
1.0
您需要執行__rtruediv__
和__rfloordiv__
。
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)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)
這些方法
被稱爲執行二進制算術運算 (+, - ,*,@,/,//%,divmod(),POW() **,< <,>>,&,^,|)與 反映(交換)的操作數。這些函數僅在左操作數不支持相應操作[3]和 操作數具有不同類型時纔會調用。 [4]例如,要評估 表達式x-y,其中y是具有方法012xx
__rsub__()
方法的類的實例,如果x.__sub__(y)
返回NotImplemented,則調用y.__rsub__(x)
。
是。您只需確保Time.__rtruediv__()
在接收到浮點數或整數時返回Frequency
實例。
用法:
>>> 100/Time(2)
Frequency(50.0)
>>> 2.5/Time(5)
Frequency(0.5)
實現:
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)
Python文檔包含implementing the arithmetic operations您的自定義類的完整示例。
處理不兼容類型的正確方法是返回特殊值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'
具有不同類每一種類型的數量聽起來像一個道路瘋狂...你是如何單元之間的不匹配處理? – jpmc26
我使用'isinstance',我只需要實現時間和頻率。 – Lucidiot