# Python __and__() Magic Method | Finxter

## Syntax

`object.__and__(self, other)`

The Python `__and__()` method implements the built-in Bitwise AND `&` operation. So, when you cal `x & y`, Python attempts to call `x.__and__(y)`. If the method is not implemented, Python first attempts to call `__rand__` on the right operand and if this isn’t implemented either, it raises a `TypeError`.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

## Background Bitwise AND &

Python’s bitwise AND operator `x & y` performs logical AND on each bit position on the binary representations of integers `x` and `y`. Thus, each output bit is 1 if both input bits at the same position are 1, otherwise, it’s 0. For example, the integer expression 4 & 3 is translated to binaries 0100 & 0011 which results in 0000 because all four input bit positions are different.

In this example, you apply the bitwise AND operator to two integers 32 and 16:

```>>> 32 & 16
0```

The expression `32 & 16` operates on the bit representations `"010000"` (decimal 32) and `"001000"` (decimal 16) and performs bitwise AND. As all i-th bit positions are different, the result is 0:

To understand this operation in detail, feel free to read over our tutorial or watch the following video:

## Example Custom __and__()

In the following example, you create a custom class `Data` and overwrite the `__and__()` method so that it returns a dummy string when trying to calculate the bitwise AND operation.

```class Data:

def __and__(self, other):
return '... my result of AND ...'

a = Data()
b = Data()

print(a & b)
# ... my result of AND ...
```

If you hadn’t defined the `__and__()` method, Python would’ve raised a `TypeError`.

## TypeError: unsupported operand type(s) for &

Consider the following code snippet where you try to calculate the right-shift operation on custom objects without defining the dunder method `__and__()`:

```class Data:
pass

a = Data()
b = Data()

print(a & b)```

Running this leads to the following error message on my computer:

```Traceback (most recent call last):
File "C:UsersxcentDesktopcode.py", line 8, in <module>
print(a & b)
TypeError: unsupported operand type(s) for &: 'Data' and 'Data'```

The reason for this error is that the `__and__()` method has never been defined—and it is not defined for a custom object by default. So, to resolve the `TypeError: unsupported operand type(s) for &`, you need to provide the `__and__(self, other)` method in your class definition as shown previously:

```class Data:

def __and__(self, other):
return '... my result of AND ...'```

Of course, you’d use another return value in practice as explained in the “Background” section.

## Python __and__ vs __rand__

Say, you want to calculate the `&` operation on two custom objects `x` and `y`:

`print(x & y)`

Python first tries to call the left object’s `__and__()` method `x.__and__(y)`. But this may fail for two reasons:

1. The method `x.__and__()` is not implemented in the first place, or
2. The method `x.__and__()` is implemented but returns a `NotImplemented` value indicating that the data types are incompatible.

If this fails, Python tries to fix it by calling the `y.__rand__()` for reverse bitwise AND on the right operand `y`.

If the reverse bitwise AND method is implemented, Python knows that it doesn’t run into a potential problem of a non-commutative operation. If it would just execute `y.__and__(x)` instead of `x.__and__(y)`, the result would be wrong because the operation may be non-commutative when defined as a custom operation. That’s why `y.__rand__(x)` is needed.

So, the difference between `x.__and__(y)` and `x.__rand__(y)` is that the former calculates `x & y` whereas the latter calculates `y & x` — both calling the respective method defined on the object `x`.

You can see this in effect here where we attempt to call the operation on the left operand `x`—but as it’s not implemented, Python simply calls the reverse operation on the right operand `y`.

```class Data_1:
pass

class Data_2:
def __rand__(self, other):
return 'called reverse bitwise AND'

x = Data_1()
y = Data_2()

print(x & y)
# called reverse bitwise AND
```

References:

## Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Latest articles

Related articles