Type conversion?

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Aug 18 14:56:47 EDT 2006


"KraftDiner" <bobrien18 at yahoo.com> wrote in message
news:1155921295.608755.269970 at i3g2000cwc.googlegroups.com...
>
> 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?

Start by repeating 50 times: "Python is not C++".

In Python, '=' is not an operator, it is a name binder, and is defined at
the language level, not at the class level.

>
> a = classA()
> b = classB()
> b = a
>
> In the end b would end up just being a refrence to a
> no conversion would have been done.
>
Just as you say, '=' will completely rebind the rhs value to the lhs name.

Now one thing you *could* do is to do something tricky, like use one of the
overridable inplace operators, like "<<=", which *is* definable by class.
Here is a type casting class that does something like you are asking for.

(Back in the CORBA days, <<= was used in the C++ binding to insert values
into a CORBA::Any variable - I guess it looks like some sort of typographic
hypodermic needle...)

-- Paul


class Caster(object):
    def __init__(self,typ):
        self.castType = typ
        self.value = self.castType()

    def cast(self,other):
        try:
            return self.castType(other)
        except Exception,e:
            print "Failed to cast '%s' as %s" % (other,
self.castType.__name__)

    # define behavior for <<= operator
    def __ilshift__(self,other):
        self.value = self.cast(other)
        return self

    def __str__(self):
        return "(%s) %s" % (self.castType.__name__,self.value)

z = Caster(int)
print z
z <<= 100
print z
z <<= 3.14159
print z
z <<= 'what the heck?'
print z


Prints:
(int) 0
(int) 100
(int) 3
Failed to cast 'what the heck?' as int
(int) None





More information about the Python-list mailing list