6

I have a class that I want to be able to do bitwise operations on in some cases.

class Measurement(object):
    def __init__(self, value = None, category = None, measure = None):
        self.value = value
        self.category = category
        self.measure = measure    

    def __nonzero__(self):
        return self.value.__nonzero__()

    def __or__(self, other):
        return self.__nonzero__() | other

a = False
b = Measurement(True)

At this point c = b | a works, but c = a | b gives a type error. How do I get it to work both ways?

Also, is there a more elegant way to do this; for example, I had hoped that by just defining __nonzero__, I might get the right behaviour, but that's not the case.

I'm using Python 2.7.

3
  • 3
    Aha, this reminds me of a similar question I saw solved. It was about implementing a multiplication operation for a custom Vector class, and the solution was to override __rmul__ (and make it call __mul__ with the arguments switched). I wonder if there's a similar solution for this. Commented Jan 11, 2017 at 18:36
  • 2
    @Tagc yes. Here is the relevant documentation. Commented Jan 11, 2017 at 18:38
  • 1
    This is the way it's suppose to be done. Explicit is better than implicit and all that... Commented Jan 11, 2017 at 18:40

1 Answer 1

2

By also defining __ror__, as shown below, I get the right behaviour. The second part of the question still stands, however. Is there a more elegant way?

def __ror__(self, other):
    return self.__or__(other)
Sign up to request clarification or add additional context in comments.

2 Comments

__ror__...I knew it.
No there isn't a better way. You could potentially define self.__ror__ = self.__or__, but I think that would just be more confusing

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.