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()
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:
You'll find other such methods for "right addition", "right subtraction", etc.
Here's another link covering the same operators:
By the way, Python does have casting operators:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With