我正在编写一个课程并希望重载__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'
然而,看起来过载什么也没做。 我做错了什么?
答案 0 :(得分:3)
__and__
方法是和运算符&
的覆盖:
>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'
答案 1 :(得分:2)
__and__
方法实际上与numeric type methods分组,因此它不代表逻辑和(and
关键字),而是{ {1}}运算符
&