Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Python Operator Overloads

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

I wrote a blog post about operator overloads in C++. Luckily for Python it is heavily document in what is called the Python Data Model. Though for the sake of having content, I’ll share some of the ones that I heavily use in my classes.

Operator Method
+ __add__(self, other)
== __eq__(self, other)
len() __len__(self)
str() __str__(self)
hash() __hash__(self)

Example Usage:

class Test:
	def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return Test(self.x, other.x)
    def __eq__(self, other):
        return self.x == other.x
    def __len__(self):
        return len(self.x)
    def __str__(self):
        return self.x
    def __hash__(self):
        return hash(self.x)
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :