Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does python have conversion operators?

I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int:

i = IntContainer(3)
i + 5

And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method.

Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++).

class IntContainer(int):
    def __init__(self,i):
        #do stuff here
        self.f = 4

    def MultiplyBy4(self):
        #some member function
        self *= self.f
        return self

print 3+IntContainer(3).MultiplyBy4()
like image 661
Alex Avatar asked Jul 12 '09 22:07

Alex


2 Answers

This should do what you need:

class IntContainer(object):
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        # do some type checking on other
        return self.x + other

    def __radd__(self, other):
        # do some type checking on other
        return self.x + other

Output:

In [6]: IntContainer(3) + 6
Out[6]: 9

In [7]: 6 + IntContainer(3)
Out[7]: 9

For more information search for "radd" in the following docs:

  • http://docs.python.org/reference/datamodel.html#special-method-names

You'll find other such methods for "right addition", "right subtraction", etc.

Here's another link covering the same operators:

  • http://www.siafoo.net/article/57#reversed-binary-operations

By the way, Python does have casting operators:

  • http://www.siafoo.net/article/57#casts

But, they won't accomplish what you need in your example (basically because methods don't have any type annotation for parameters, so there's no good way to cast implicitly). So you can do this:

class IntContainer2(object):
    def __init__(self, x):
        self.x = x

    def __int__(self):
        return self.x


ic = IntContainer2(3)
print int(ic) + 6
print 6 + int(ic)

But this will fail:

print ic + 6  # error: no implicit coercion
like image 128
ars Avatar answered Oct 16 '22 06:10

ars


You won't get conversion operators like in C++ because Python does not have this kind of strong static type system. The only automatic conversion operators are those which handle default numeric values (int/float); they are predefined in the language and cannot be changed.

Type "conversion" is usually done by constructors/factories. You can then overload standard methods like __add__ to make it work more like other classes.

like image 34
liori Avatar answered Oct 16 '22 06:10

liori