Python重载对象.__和___方法

时间:2017-05-10 11:32:20

标签: python python-2.7

我正在编写一个课程并希望重载__and__函数

class Book(object):
    def __init__(self, name, pages):
        self.name = name
        self.pages = pages

    def __and__(self, other):
        return '{}, {}'.format(self.name, other.name)

当我运行时

Book('hamlet', 50) and Book('macbeth', 60)

我希望得到' hamlet,macbeth'

然而,看起来过载什么也没做。 我做错了什么?

2 个答案:

答案 0 :(得分:3)

__and__方法是和运算符&的覆盖:

>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'

可悲的是,你can not override the and operator

答案 1 :(得分:2)

__and__方法实际上与numeric type methods分组,因此它不代表逻辑和(and关键字),而是{ {1}}运算符

&