output formatting for classes

Schüle Daniel uval at rz.uni-karlsruhe.de
Thu Mar 9 20:19:10 EST 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. Can I somehow overload the "%" operator for that? Thanks.
> 
> On an unrelated matter, I think the complex class in Python is too
> complex, so I plan to clean it up and implement it right. (just
> kidding, folks!)

yeah, i miss some things in complex implementation
for example c=complex()
c.abs = 2**0.5
c.angle = pi/2

should result in 1+1j :)

or c=complex(1,1)
print c.abs # should print 2**0.5
print c.angle # should print pi%2

i think one can implement it with properties

but to your question ...

 >>> class X(object):
...     def __float__(self):
...             return 1.0
...     def __long__(self):
...             return 10l
...     def __int__(self):
...             return 20
...     def __repr__(self):
...             return "i am"
...     def __str__(self):
...             return "I AM"
...     def __complex__(self):
...             return 1+1j
...
 >>> x=X()
 >>> int(x)
20
 >>> long(x)
10L
 >>> float(x)
1.0
 >>> str(x)
'I AM'
 >>> repr(x)
'i am'
 >>> print "%s -- %r" % (x,x)
I AM -- i am
 >>> complex(x)
(1+1j)
 >>>




More information about the Python-list mailing list