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