Python Tutorial_ Inheritance
Python Tutorial_ Inheritance
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
Inheritance
Having a function with a different number of parameters is another way of function overloading. The following C++ program shows such an example. The function f can be called with either one or two integer
arguments:
#include <iostream>
using namespace std;
int main() {
int f(int n) {
return n + 42;
}
int f(int n, int m) {
return n + m + 42;
}
This doesn't work in Python, as we can see in the following example. The second definition of f with two parameters redefines or overrides the first definition with one argument. Overriding means that the first
definition is not available anymore. This explains the error message:
The * operator can be used as a more general approach for a family of functions with 1, 2, 3, or even more parameters:
def f(*x):
if len(x) == 1:
return x[0] + 42
else:
return x[0] + x[1] + 42
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein