I have been converting a C++ plugin to Python and I came across some C++ code that I was unsure how to convert to Python. I needed to overload several operators like +, -, <<, and [] so how does one go about this? First thing which is always best is to find the python.org help docs.
http://www.python.org/doc/2.5.2/ref/numeric-types.html
Unfortunately they dont have any good examples so I went searching for more. And here is an example I compiled after my search concluded. The lambda function might seem a bit confusing at first but it simply defines two variables ( in this case ) then it runs an expression and at the end of it, it defines what those variables are. The map() function is even more simple. map() can run a function on a list. For example:
#map() example
def add_one(a):
return (a+1)
foo = [1,2,3,4]
foobar = map(add_one, foo)
print foobar
>>[2, 3, 4, 5]
lambda is special in that it is a function and operates on lists so its allowed to be inside of map()
#lambda example
foo = [1,2,3,4]
bar = [1,2,3,4]
foobar = lambda x, y: x + y, foo, bar
print foobar
( at 0x0000000017A9BEB8>, [1, 2, 3, 4], [1, 2, 3, 4])
And last here is the overload operators example:
Continue reading »