在Python中按类的实例除数 [英] Dividing a number by instances of my class in Python

查看:33
本文介绍了在Python中按类的实例除数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Time 的类,并且需要实现一个 Frequency 类.如何实现将 int s或 float s除以 Time 的实例以获得 Frequency 的实例?

I have a class called Time, and I need to implement a Frequency class. How can I implement dividing ints or floats by an instance of Time to get an instance of Frequency ?

我已经了解 __ div __ __ truediv __ __ floordiv __ 和其他Python特殊方法,并且我已经在代码中使用它们来划分实例按数字或其他类的实例划分类,但我找不到一种方法将数字除以我的类的实例.

I already know about __div__, __truediv__, __floordiv__ and other Python special methods, and I already use them in my code to divide instances of classes by numbers or instances of other classes, but I cannot find a way to divide a number by an instance of my class.

是否可以在Python中实现将数字除以类的实例?

Is it possible to implement dividing a number by an instance of a class in Python ?

推荐答案

您正在寻找 __ rtruediv __ 方法.当执行 x/y 时,如果 type(x)没有实现 __ div __(self,other)方法,而 other 可以是 type(y)类,然后执行 type(y).__ rtruediv __(y,x),并返回其结果.

The __rtruediv__ method is what you're looking for. When x / y is executed, if type(x) does not implement a __div__(self, other) method where other can be of class type(y), then type(y).__rtruediv__(y, x) is executed, and its result is returned.

用法:

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

这篇关于在Python中按类的实例除数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆