我正在编写一个类,想要重载__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)
我希望得到"哈姆雷特,麦克白">
但是,重载似乎没有任何作用。我做错了什么?
__and__
方法是 and 运算符&
的重写:
>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'
遗憾的是,您无法覆盖and
运算符。
__and__
方法实际上与数值类型方法分组,因此它不表示逻辑和(这是and
关键字(,而是&
运算符
>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'