Programming Tutorials

Overloading in python

By: Mariyan in Python Tutorials on 2012-04-07  

Python supports function overloading in a different way than many other programming languages like Java or C++. In Python, you cannot create multiple functions with the same name and different parameter lists. Instead, you can define a single function with a variable number of arguments, and then use conditional statements to handle the different argument types.

Here's an example:

def my_function(*args):
    if len(args) == 1:
        # Handle the case where a single argument is passed
        print("You passed a single argument:", args[0])
    elif len(args) == 2:
        # Handle the case where two arguments are passed
        print("You passed two arguments:", args[0], "and", args[1])
    else:
        # Handle the case where more than two arguments are passed
        print("You passed", len(args), "arguments:", args)

my_function(1)
my_function(1, 2)
my_function(1, 2, 3, 4)

In this example, my_function() takes a variable number of arguments using the *args syntax. The function then uses conditional statements to handle the different argument types.

Another way to achieve a similar effect in Python is to use default arguments. Default arguments are values that are assigned to function arguments by default if no value is provided by the caller. You can use this feature to define a single function that behaves differently depending on the values of the default arguments.

Here's an example:

def my_function(arg1, arg2=None):
    if arg2 is None:
        # Handle the case where a single argument is passed
        print("You passed a single argument:", arg1)
    else:
        # Handle the case where two arguments are passed
        print("You passed two arguments:", arg1, "and", arg2)

my_function(1)
my_function(1, 2)

In this example, my_function() takes two arguments, but the second argument has a default value of None. If the caller does not provide a value for the second argument, the function behaves as if it were called with a single argument.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)