Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python custom class operator overloading

suppose I have a class:

class Cat:
    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

I also have a list of Cats:

l = [Cat('Joe')]

Now I can't call the following:

if 'Joe' in l: # the right syntax would be if Cat('Joe') in list

Which operator do I need to overload to be able to identify objects of class Cat by their member variable name?

like image 946
gen Avatar asked Aug 13 '13 13:08

gen


People also ask

How do you overload an operator in a class Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

How does a Python class handle operator overloading in Python?

Python operators work for built-in classes. But the same operator behaves differently with different types. For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

Can you overload classes in Python?

Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

Does Python support overloaded operators?

We can overload all existing operators but we can't create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator.


1 Answers

You have to define the __eq__ method, as shown below:

class Cat:

    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        elif isinstance(other, Cat):
            return self.name == other.name

So that when you run your check:

l = [Cat('Joe')]

'Joe' in l
#True
like image 81
Saullo G. P. Castro Avatar answered Sep 29 '22 00:09

Saullo G. P. Castro