2

say I want to overload an operator (lets say + for now) for some class I've created,

class A (object):
    #code here

and then:

a = A()
b = A()

what would I do to define:

c = a + b

or something along those lines? (note: this question is purely theoretical I will likely use this at some time, just not currently (unless its really easy and I really need a use for it))

(p.s. if it is possible to do this for other things such as and, or, not, str, e.t.c.)

1 Answer 1

4

Since A is the first operand of the binary operator, you should define A.__add__(). If A was the second operand and there was no way to change the class of the first operand, you would have to define A.__radd__().

Full reference for magic methods

Sign up to request clarification or add additional context in comments.

5 Comments

thank you, is their a way to do this for and or or or not?
lets say I would like to def __pow__(self, y) outside of a class. Better yet redefine it for say the list type. How would I do that? is it even possible?
Defining methods outside a class and monkeypatching them after is possible. Doing it with a magic method is questionable. But monkeypatching a type defined in C is impossible.
oh! I didn't know lists were predefined in C!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.