Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python重载对象._和_方法_Python_Python 2.7 - Fatal编程技术网

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当然没有,我只是为了完整性才提到这一点。