2

I'm writing a class and want to overload the __and__ function

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

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

When I run this

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

I would expect to get 'hamlet, macbeth'

However, it appears the overload does nothing. What am I doing wrong?

Alon
  • 743
  • 10
  • 23

2 Answers2

4

The __and__ method is an override for the and operator &:

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

Sadly, you can not override the and operator.

Community
  • 1
  • 1
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
3

The __and__ method is actually grouped with the numeric type methods, therefore it does not represent logical and (which is the and keyword) but rather the & operator

>>> Book('hamlet', 50) & Book('macbeth', 60)
'hamlet, macbeth'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218