[Tutor] how to get str() to use my function?

James Mills prologic at shortcircuit.net.au
Wed Aug 4 16:46:51 CEST 2010


On Thu, Aug 5, 2010 at 12:37 AM, Alex Hall <mehgcap at gmail.com> wrote:
> Hi all,
> I have a card class. A card object simply consists of a pair of
> numbers; 0,0 might be the ace of clubs, for example. I have a toString
> method in my card class. Is there a way to just say str(card) instead
> of card.toString()? Maybe some sort of basic, built-in function to
> override? TIA. Oh, what about doing the same with operators? For
> example, could I get the program to call my own math functions when it
> sees a card object in a math expression, like
> if(card1==card2)

implement a __str__ method. For example:

$ python
Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
[GCC 4.4.4 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     def __str__(self):
...             return "<Foo>"
...
>>> foo = Foo()
>>> foo
<__main__.Foo object at 0x83d796c>
>>> str(foo)
'<Foo>'
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"


More information about the Tutor mailing list