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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But you could override __bool__ / __nonzero__
@timgeb That wouldn't help do what the OP is trying to do.
@khelwood of course not, I just mentioned this for completeness.
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.