如何重载`浮动()`在Python中的自定义类?(How to overload `float()`

2019-09-16 08:56发布

摘要

我怎样才能过载内置的float我的课,所以当我打电话float()在它的一个实例,我的自定义函数被调用,而不是默认的内置?

我的课

嗨,我编码我自己的Fractions类(任意高浮点运算精度)。 它是这样的(我还没有说完的话):

class Fractions:
    """My custom Fractions class giving arbitarilly high precision w/ floating-point arithmetic."""

    def __init__(self, num = 0, denom = 1):
        """Fractions(num = 0, denom = 1) -> Fractions object

        Class implementing rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3.
        Both arguments must be rational, i.e, ints, floats etc. .The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.

        Fractions can also be constructed from:
        - numeric strings that are valid float constructors (for example, '-2.3' or '1e10')
        - strings of the form '123/456'"""
        if '/' in str(num):
            self.num, self.denom = map(float, num.split('/'))  #'x/y'
        else:
            self.num, self.denom = float(num), float(denom)    #(num, denom)
        self.normalize()

    def __repr__(self):
        print self.num + '/' + self.denom

    def __invert__(self):
        self.num, self.denom = self.denom, self.num

    def normalize(self):
        num, denom = self.num, self.denom
        #Converting `num` and `denom` to ints if they're not already
        if not float(num).is_integer():
            decimals = len(str(float(num) - int(num))) - 1
            num, denom = num*decimals, denom*decimals
        if float(denom).is_integer():
            decimals = len(str(float(denom) - int(denom))) - 1
            num, denom = num*decimals, denom*decimals
        #Negatives
        if denom < 0:
            if num < 0:
                num, denom = +num, +denom
            else:
                num, denom *= -1
        #Reducing to the simplest form
        from MyModules import GCD
        GCD_ = GCD(num, denom)
        if GCD_:
            self.num, self.denom /= GCD_
        #Assigning `num` and `denom`
        self.num, self.denom = num, denom

问题

现在,我想要实现重载的方法float()即,当我的类的实例传递给它被称为float() 我怎么做? 起初我以为:

def float(self):
    return self.num/self.denom

但是,这并不能正常工作。 也没有谷歌的搜索或Python的文档帮助。 它甚至有可能实现吗?

Answer 1:

定义__float__()的特殊方法对您的类。

class MyClass(object):
    def __float__(self):
         return 0.0

float(MyClass())   # 0.0

注意,此方法必须返回一个float ! 计算self.num / self.denom ,返回一个int默认在之前3.0的Python版本假设两个操作数都是整数。 在这种情况下,你只要确保其中一个操作数是float: float(self.num) / self.denom例如。



文章来源: How to overload `float()` for a custom class in Python?