Make object return float value python -
i can't think of similar in other language python can this...
what need following:
when referencing object's value, need object return float. eg:
b = anyobject(3, 4) print(b) #should output 0.75
i have tried following:
def __get__(self, instance, owner): return float(self.param1/self.param2)
but not work. when printing b this, object's reference:
<(...) object @ 0x10fa77e10>
please help! thanks
you're seeing <fraction object @ 0xdeadbeef>
because that's __str__
method of object
class returns in python implementation: class name , address. make print
work, need override __str__
method own code replace method inherited object
. , while you're @ it, can make float(obj)
work implementing __float__
method.
from __future__ import division class fraction(object): def __init__(self, num, den): self.num, self.den = num, den # built-in function float(obj) calls obj.__float__() def __float__(self): """float(self): return float approximating fraction.""" return self.num / self.den # python 2.6/2.7/3.x print() function , python 2 print statement # call str(obj), calls obj.__str__() def __str__(self): """str(self): return string representing fraction.""" return str(float(self))
Comments
Post a Comment