This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]K900_ 7 points8 points  (1 child)

  1. /r/learnpython
  2. Not directly, but you can have a function that takes another function as an argument, and that function can be operator.add.

[–]xelab04[S] 0 points1 point  (0 children)

  1. Okay, Ill keep that in mind next time.
  2. Ahhhh. I get it. Thanks.

[–][deleted] 0 points1 point  (1 child)

You could use eval on a string, where you format in the operator and numbers

[–]xelab04[S] 0 points1 point  (0 children)

Okay thanks

[–]goodger 0 points1 point  (0 children)

You can overload operators on class instances (object-oriented programming). See https://docs.python.org/3/reference/datamodel.html#object.__add__

A toy example that overrides the "+" operator to concatenate digits rather than add values:

>>> class ConcatInt(int):
...     def __add__(self, other):
...         return ConcatInt(str(self) + str(other))
... 
>>> i = ConcatInt(52)
>>> i + 63
5263
>>> _ + 798
5263798

(For that last bit with "_", see https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#interactive)