Python does not support traditional function overloading as seen in other languages like C++ or Java. Instead, it allows similar behavior using default arguments and variable-length arguments.
*args and **kwargs to accept arbitrary numbers of positional and keyword arguments.Default arguments allow you to define functions that can be called with different numbers of arguments.
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Welcome") # Output: Welcome, Bob!
message has a default value of "Hello".greet with just the name or both name and message.Variable-length arguments enable functions to handle more flexible input.
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3)) # Output: 6
print(add_numbers(10, 20, 30, 40)) # Output: 100
*args: Collects all positional arguments into a tuple.sum() to add all numbers.You can combine default and variable-length arguments for greater flexibility.
def display_info(name, age=30, *hobbies):
print(f"Name: {name}, Age: {age}")
if hobbies:
print("Hobbies:", ", ".join(hobbies))
display_info("Alice", 25, "Reading", "Cycling")
# Output: Name: Alice, Age: 25
# Hobbies: Reading, Cycling
display_info("Bob")
# Output: Name: Bob, Age: 30
age): Has a default value of 30.*hobbies: Accepts any number of additional arguments, which are treated as hobbies.**kwargsUsing **kwargs, you can accept any number of keyword arguments.
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Alice", age=25, city="New York")
# Output: name: Alice
# age: 25
# city: New York
**kwargs: Collects keyword arguments into a dictionary.