Type conversion?

Duncan Booth duncan.booth at invalid.invalid
Fri Aug 18 13:38:43 EDT 2006


KraftDiner wrote:

> In C++ you can cast one class type to another if you override the
> operator=
> Then you can convert one class type to another...
> In Python it would appear that the left hand side of the assignment
> operator
> is not used to determine if a cast is necessary.
> So how would I do this in python?
> 
> a = classA()
> b = classB()
> b = a
> 
> In the end b would end up just being a refrence to a

(You aren't quite correct there: the name 'b' would refer to the same 
object as is referred to by the name 'a'. However there is nothing 
associating the two names 'b' and 'a', so no reference from 'b' to 'a'.)

> no conversion would have been done.

You just have to call the appropriate constructor:

b = classB(a)

So long as the constructor for classB knows how to create an instance from 
a classA instance this will have the desired effect.

So:

aStr = str(anInt)
aFloat = float(anInt)

...and so on...



More information about the Python-list mailing list