如何在Python中为自定义类重载`float()`?

Yat*_*wal 9 python floating-point overloading operator-overloading

摘要

如何重载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
Run Code Online (Sandbox Code Playgroud)

问题

现在,我想实现一个重载的方法float(),即在传递我的类的实例时调用它float().我怎么做?起初我想:

def float(self):
    return self.num/self.denom
Run Code Online (Sandbox Code Playgroud)

但那没用.谷歌搜索或Python文档都没有帮助.它甚至可以实现吗?

kin*_*all 18

__float__()在您的班级上定义特殊方法.

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

float(MyClass())   # 0.0
Run Code Online (Sandbox Code Playgroud)

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