I'm learning python currently, earlier I worked on C++. Today I was watching a tutorial on Python concepts, and I saw this code which although works fine on Python but should've given error according to me (or more frankly, according to C++).
Here is the C++ code, which gives error: (Please check out the output below first)
#include<iostream>
int doMath(int a, int b){
return a+b;
}
int doMath(int c, int d){
return c*d;
}
int main(){
std::cout<<doMath(3,4);
return 0;
}
Output:
In function 'int doMath(int, int)':
error: redefinition of 'int doMath(int, int)' at line 9
note: 'int doMath(int, int)' previously defined at line 5
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===
And here is the equivalent Python code: (Please check out the output below first)
def doMath(a,b):
return a+b
def doMath(c,d):
return c*d
def main():
print(doMath(3,4))
if __name__ == "__main__": main()
Output:
12
Process finished with exit code 0
So why does python select the second-in-sequence function definition of doMath() on its own? How could it decide by itself that I want the second definition and not first?? Why does it allow multiple definitions under same name and same number of parameters???
Or more precisely, perhaps the question could be, why can't we compile a Python code like we can in C++ (atleast not on PyCharm or few others I know)? Because if we could it would first compile and identify that there are two function definitions under one name with same number of parameters and thus not run at all. Same as good old fashioned C.