does python have conversion operators?

operators, python

Solution

sometimes maybe just subclass from int directly is enough. then `__add__` and `__radd__` need not costuming.

class IntContainer(int):
    pass
i = IntContainer(3)
print i + 5 # 8 
print 4 + i # 7

class StrContainer(str):
    pass
s = StrContainer(3)
print s + '5' # 35
print '4' + s # 43

Problem

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() ```

Original source