Can someone please tell me how I can use this piece of code?. I’m not sure what question it is I want to ask, I just want to define the class needed to play with it along with other commands that I can give to the interpreter.
This is really making my headspin, because there is no other supporting code for it and I think it might be a metaclass usage.
Thank you,
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
A method called
__new__is the constructor for the class. Don’t confuse it with__init__which is the class initialiser; the difference is that__new__is called before you have an instance of the object and must create and return the instance whereas__init__is called after the object has been created.Usually when you subclass you just override the initialiser to do your own initialisation, but that often doesn’t work if you are subclassing an immutable object as you cannot change the actual value of the object after it has been constructed. In this case the code is changing how the float is constructed so it overrides
float.__new__and then calls it explicitly with a modified argument.The whole class is a complete waste of time, if you want to create a rounded float just do this:
or:
and in either case a call to rounded_float returns the value rounded to 2 digits.
Also remember when you are using this function that
rounded_float(1.0/3.0)doesn’t give you exactly0.33it just gives you the nearest floating point representation. If you want the exact value for calculation purposes use theDecimalclass, but if it is for output then just format the number on output.