operator overload python custom class

时光总嘲笑我的痴心妄想 提交于 2019-12-22 01:40:08

问题


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:


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



来源:https://stackoverflow.com/questions/24564610/operator-overload-python-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!