How can I make a class that can be converted into an int?
Peter Otten
__peter__ at web.de
Mon Oct 2 11:14:35 EDT 2006
Matthew Wilson wrote:
> 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.
>>> class C(object):
... def __int__(self): return 42
...
>>> int(C())
42
> For string conversion, I just define the __str__ method. What's the
> equivalent for int? For float, too, while I'm at it?
http://docs.python.org/ref/numeric-types.html
Peter
More information about the Python-list
mailing list