__xor__Easy Examples

Defines behavior for the ^ bitwise XOR operator

Implementing __xor__

Basic implementation of __xor__ in a class.

python
class Example:
    def __xor__(self):
        return "Example __xor__"

obj = Example()
print(obj)

__xor__ defines behavior for the ^ bitwise xor operator. Implementing it lets you customize how Python interacts with your objects.

__xor__ in action

Seeing __xor__ called by Python's built-in operations.

python
# How Python calls __xor__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __xor__(self, other):
        print(f"__xor__ was called!")
        return self

d = Demo(42)
# This triggers __xor__:
print(d)

Python automatically calls __xor__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground