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

M

Matthew Wilson

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?

TIA

Matt
 
M

Mikael Olofsson

Matthew said:
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

From Python Reference Manual, section 3.4.7 Emulating numeric types:

__complex__( self)
__int__( self)
__long__( self)
__float__( self)
Called to implement the built-in functions complex(), int(),
long(), and float(). Should return a value of the appropriate type.

/MiO
 
P

Peter Otten

Matthew said:
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.
.... def __int__(self): return 42
....
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
 
T

Tim Chase

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?
.... def __str__(self): return "I'm a string"
.... def __int__(self): return 42
.... def __float__(self): return 3.14159
...."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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top