如何在Python中为自定义类重载`float()`? [英] How to overload `float()` for a custom class in Python?

查看:199
本文介绍了如何在Python中为自定义类重载`float()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小结



如何为我的类重载内置的 float ,所以当我调用<$我的自定义函数被调用,而不是默认的内置?



我的类



我编写了我自己的 Fractions 类(用于任意高的浮点运算精度)。它是这样的(我还没有完成):

  class分数:
我的自定义分数类赋予了高精度的浮点运算。

def __init __(self,num = 0,denom = 1):
分数(num = 0 ,denom = 1) - >分数对象

实现有理数的类在构造函数的双参数形式中,分数(8,6)将产生一个等于4/3的有理数。
这两个参数必须是合理的,即int,float等等。分子默认为0,分母默认为1,使得Fraction(3)== 3和Fraction()== 0.

分数也可以从以下构造:
- 有效的浮点构造函数(例如-2.3或1e10)的数字字符串
- 形式为123/456
if 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
$ b $ def __invert __(self):
self.num,self.denom = self。 denom,self.num

def normalize(self):
num,denom = self.num,self.denom
#转换`num`和`denom`来输入if他们不是
,如果不是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 *小数,denom *小数
#负数
如果denom < 0:
如果num < 0:
num,denom = + num,+ denom
else:
num,denom * = -1
#从MyModules中减去最简单的形式
import GCD
GCD_ = GCD(num,denom)
如果GCD_:
self.num,self.denom / = GCD_
#分配`num`和`denom`
self.num,self.denom = num,denom



问题



现在,我想实现一个重载 float()的方法,即当我的类的一个实例被传递给浮动()。我怎么做?起初我想:

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

但是这并不奏效。 Google搜索或Python文档都没有帮助。它甚至有可能实现它吗?

解决方案

定义 __ float __() 特殊的方法。 b

  class MyClass(object):
def __float __(self):
return 0.0

float(MyClass())# 0.0

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

Summary

How can I overload the built-in float for my class so when I call float() on an instance of it, my custom function gets called instead of the default built-in?

My Class

Hi, I was coding my own Fractions class (for arbitrarily-high floating-point operation precision). It goes like this (I haven't yet finished it):

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

The Question

Now, I want to implement a method that overloads float(), i.e., it is called when an instance of my class is passed to float(). How do I do that? At first I thought:

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

But that didn't work. Neither did a Google Search or the Python Docs help. Is it even possible to implement it?

解决方案

Define the __float__() special method on your class.

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

float(MyClass())   # 0.0

Note that this method must return a float! The calculation self.num / self.denom, returns an int by default in versions of Python prior to 3.0 assuming both operands are integers. In this case you'd just make sure one of the operands is a float: float(self.num) / self.denom for example.

这篇关于如何在Python中为自定义类重载`float()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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