Menu
CoddyTech

Defaults Instead of Overloads

Lesson 23 of 48 in Coddy's Python for Java Developers course.

Replace simple overload families with parameter defaults where that expresses the API. Java has no ordinary default parameter values or keyword argument calls; Python supports both. Keyword arguments bind by parameter name, so their order may differ from the signature. A normal positional argument comes before named ones, and each parameter may receive only one value. Default expressions are evaluated when def executes, not afresh at each call. An immutable default such as 1 is safe for this task.

Java excerpt: class member declarations

// Class members
static int cost(int price) { return cost(price, 1); }
static int cost(int price, int quantity) { return price * quantity; }

Python

def cost(price, quantity=1):
    return price * quantity
print(cost(4))
print(cost(quantity=3, price=4))

Watch the difference

Never use [] as a default when each call needs its own new list. Use None and create the list inside the function. Java overload resolution and Python argument binding are different mechanisms.

Practice

Apply this comparison in the task below. Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Implement line_cost(price, quantity=1, discount=0), returning integer price * quantity - discount. Inputs are nonnegative and discount is at most the product. The driver reads price, quantity, and discount, calls once with price only, once with two positional arguments, and once with reordered keyword arguments, then prints the results. These defaults and named calls replace a Java overload family.

Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

Try it yourself

from functions import line_cost

price = int(input())
quantity = int(input())
discount = int(input())
print(line_cost(price))
print(line_cost(price, quantity))
print(line_cost(discount=discount, price=price, quantity=quantity))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler