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
BeginnerImplement 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler