Bitwise Operator Overloading
00:00 In the previous lesson, I showed you how byte orders are related to boiled eggs. In this lesson, I’ll show you how to use the special methods inside of Python objects to overload bitwise operators.
00:13 Everything in Python is an object. All the interactions between objects that look like operations—adding, subtracting, comparisons, et cetera—are actually mappings to special methods on those objects.
These special methods all start with double underscores (
__), sometimes referred to as dunder. For bitwise operators, the special methods are
Let’s go play with these in the REPL. In the top window here, I’ve created a new class called
FourBit. In the spirit of the four-bit adder in a previous lesson, I’ve created an object that stores only four bits. Note the little bit of trickiness in the declaration of the class.
int class uses a variable called
num to store the value, so the initializer starting on line 3 does the same thing. I’ve added a quick check in the initializer to make sure nobody tries to create a four-bit object with a value that is bigger than what can be stored in four bits. Let me start out by importing this into the REPL,
This is what is called when two
FourBit objects are added together. The other argument is the object being added to this one. Line 18 adds our
num value to the other object’s
num value, then masks it to make sure it stays as four bits.
And all those bits flipped to zero. Nice! For a little homework, you could take the code from the
FourBit adder from the skippable section and re-implement the
.__add__() method to use your digital circuit simulator.
The overloading I’ve done is to make an actual numeric object do bitwise things, but you’re not limited to that. Lots of objects overload bitwise operations to mean different things. For example, the
frozenset objects overload OR and AND (
&) to mean set union and intersection, respectively.
Become a Member to join the conversation.