python中如何定义float_如何重载Python中自定义类的float()?

摘要

如何重载类的内置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文档都没有帮助。甚至有可能实施吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值