Python重载对象._和_方法
我正在编写一个类,希望重载_和_函数Python重载对象._和_方法,python,python-2.7,Python,Python 2.7,我正在编写一个类,希望重载_和_函数 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('
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运算符的重写
&
:
>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'
遗憾的是,您。该
\u和
方法实际上是与的分组的,因此它并不表示逻辑and(即和
关键字),而是表示和运算符
>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'
但是你可以覆盖\uuuubool\uuuu/\uuuuuuuu nonzero\uuuuuu
@timgeb,这无助于完成OP试图做的事情。@khelwood当然没有,我只是为了完整性才提到这一点。