问题
Okay, I want to use repr() to print out a text version of a bunch of lists and nested arrays.
But I want the numbers to have only 4 decimal places not: 42.7635745114 but 32.7635.
I'd like to use repr() because of its nice ability to handle nested arrays. Writing my own print loop is an unattractive option.
Surely there is some way to overload repr to do this? I see there is a repr and reprlib modules but examples are really scarce, like nonexistent.
回答1:
No, there is no way to overload repr()
. The format for floats is hardcoded in the C source code.
The float_repr() function calls a helper function with the 'r'
formatter, which eventually calls a utility function that hardcodes the format to what comes down to format(float, '.16g')
.
You could subclass float
, but to only do that for representing values (especially in a larger structure) is overkill. This is where repr
(reprlib
in Python 3) comes in; that library is designed to print useful representations of arbitrary data structures, and letting you hook into printing specific types in that structure.
You could use the repr
module by subclassing repr.Repr(), providing a repr_float()
method to handle floats:
try: # Python 3
import reprlib
except ImportError: # Python 2
import repr as reprlib
class FloatRepr(reprlib.Repr):
def repr_float(self, value, level):
return format(value, '.4f')
print(FloatRepr().repr(object_to_represent))
Demo:
>>> import random
>>> import reprlib
>>> class FloatRepr(reprlib.Repr):
... def repr_float(self, value, level):
... return format(value, '.4f')
...
>>> print(FloatRepr().repr([random.random() for _ in range(5)]))
[0.5613, 0.9042, 0.3891, 0.7396, 0.0140]
You may want to set the max*
attributes on your subclass to influence how many values are printed per container type.
回答2:
Maybe you could try string formatting using return "%.4f" %(self.float)
:
>>> class obj:
... def __init__(self, value):
... self.float = value
... def __repr__(self):
... return "%.4f" %(self.float)
...
>>> x = obj(8.1231231253252)
>>> x.float
8.1231231253252
>>> x
8.1231
>>>
来源:https://stackoverflow.com/questions/24187684/python-change-repr-floating-digits