output formatting for user-defined types
Peter Hansen
peter at engcorp.com
Wed Apr 5 21:11:47 EDT 2006
Russ wrote:
> I'd like to get output formatting for my own classes that mimics the
> built-in output formatting. For example,
>
>
>>>>x = 4.54
>>>>print "%4.2f" % x
>
>
> 4.54
>
> In other words, if I substitute a class instance for "x" above, I'd
> like to make the format string apply to an element or elements of the
> instance. Is that possible? If so, how? Thanks.
I believe implementing the special method __float__ on your class
should be sufficient.
class X:
def __float__(self):
return 3.14
>>> print '%f' % X()
3.140000
-Peter
More information about the Python-list
mailing list