zhihuifan
zhihuifan

Reputation: 1113

how does python operator overloading works

I can understand that some langurage allows user to do some operator overloading. I know this in C++ area first. But c++ also has some restrictions on operator overloading and I think that's reasonable.

but when I come to python pandams library. I'm start to confused.

Take a look at my code at nbviewer.jupyter.org

complaints['Complaint Type'] == "Noise - Street/Sidewalk"

doesn't return a True or False.

This is crazy to me. Does anyone can help me to understand this?

  1. in Python, can we overloading operator == so that it doesn't return a boolean?
  2. If it is true for question 1, how can I wrote a simple code to demo this?

Some relevant results copied from the link:

>>> complaints['Complaint Type'] == "Noise - Street/Sidewalk"

0      True
1     False
2     False
3     False
4     False
...

111063    False
111064    False
111065    False
111066     True
111067    False
111068    False
Name: Complaint Type, Length: 111069, dtype: bool

Upvotes: 2

Views: 450

Answers (1)

srowland
srowland

Reputation: 1705

You can overload operators if you create your own classes and add a __eq__ method to them.

class MyClass(object):

    def __eq__(self, other):
        # compare self with other, return whatever you need

This will be invoked whenever you compare your type with self == other. It is considered very normal to return a boolean from this function in python, so you might want to have a think about returning anything else if you want your code to make sense to other developers.

See the docs for python 2 on this here

Upvotes: 3

Related Questions