热线电话:13121318867

登录
2019-02-19 阅读量: 659
如何在Python中重载binary 运算符?

当我们在用户定义的数据类型上使用运算符时,会自动调用与该运算符关联的特殊函数或魔术函数。改变运算符的行为就像改变方法或函数的行为一样简单。您可以在类中定义方法,并且运算符根据方法中定义的行为进行工作。当我们使用+运算符时,__add__会自动调用magic方法,其中定义了+运算符。通过改变这个魔术方法的代码,我们可以为+运算符赋予额外的意义。

# Python Program illustrate how

# to overload an binary + operator

class A:

def __init__(self, a):

self.a = a

# adding two objects

def __add__(self, o):

return self.a + o.a

ob1 = A(1)

ob2 = A(2)

ob3 = A("Geeks")

ob4 = A("For")

print(ob1 + ob2)

print(ob3 + ob4)

输出:

3
GeeksFor
0.0000
3
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子