How can I make a class that can be converted into an int?

Tim Chase python.list at tim.thechases.com
Mon Oct 2 17:17:44 CEST 2006


> What are the internal methods that I need to define on any class so that
> this code can work?
> 
> c = C("three")
> 
> i = int(c) # i is 3
> 
> I can handle the part of mapping "three" to 3, but I don't know what
> internal method is called when int(c) happens.
> 
> For string conversion, I just define the __str__ method.  What's the
> equivalent for int?  For float, too, while I'm at it?

Is it too unkind to say it's semi-obvious?

 >>> class Impersonator(object):
...     def __str__(self): return "I'm a string"
...     def __int__(self): return 42
...     def __float__(self): return 3.14159
...
 >>> c = Impersonator()
 >>> float(c)
3.1415899999999999
 >>> int(c)
42
 >>> str(c)
"I'm a string"

You say you can handle the conversion of "three" to 3, so I leave 
that implementation of __int__(self) to you... :)

-tkc






More information about the Python-list mailing list