摘要
我怎样才能过载内置的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的文档帮助。 它甚至有可能实现吗?