Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to define two methods with the same name but different returning types?

Tags:

python

I've written a piece of code to determine a typical palindrome string. I did this by the definition of a reverse() method returning a string. I am also eager to have the same method, but in the void form, because of some future needs.

As I add the latter to the code, the valid output will become invalid. Is it legal to define two methods with the same name, but different returning types?

If not, how can I write this code with the void-type method?

class detector(object):
    def __init__(self,string):
        self.string = string

    forbidden = (' ','!','?','.','-','_','&','%',"#",",")

    def eliminator(self):
        for item in self.forbidden:
            if item in self.string:
                self.string = self.string.replace(item,"")

    def reverse(self):
        return self.string[::-1]

    #def reverse(self):
    #    self.string = self.string[::-1]    I am prone to add this method

    def check(self):
        reversed = self.reverse()
        if self.string == reversed:
            print("Yes")
        else:
            print("No")

det = detector("rise to vote, sir!")
det.eliminator()
det.check()

When I add the outcommented lines, the valid "Yes" becomes "No"!


2 Answers

It is legal to write that, but it doesn't define two methods. The last definition overwrites the first, so only the last one exists and that one will always be called. It is the same as if you did

x = 1
x = 2

The first assignment is obliterated by the second.

As for your larger question: The way to have two methods that return different things is to define two methods with different names. Python does not know anything about the types that a function "intends" to return. There is no such thing as a "void-type method".

like image 137
BrenBarn Avatar answered Dec 12 '25 06:12

BrenBarn


If you call two methods, Python will override the first one made, leaving just the second one defined:

>>> def foo():
...     return 1
...
>>> def foo():
...     return 2
...
>>> foo()
2
>>>

Basically, the second one overrides the first.

To see why Python would do this, take it from a common sense standpoint. Say you have a homework assignment, which is online, and when you get to it, there are two assignments under the same name. How would you know which one to pick? Basically, Python just picks the most recent one, which is the smart choice.

Also, when calling the function, how do you think Python would understand which one you want if they both have the same name?

Python may be a smart language, but it is by no means psychic :)

like image 41
A.J. Uppal Avatar answered Dec 12 '25 06:12

A.J. Uppal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!