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
?
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 == .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With