To learn about providing optional arguments in your functions and methods using an undefined number of positional arguments or an undefined number of keyword arguments, check out Using Python Optional Arguments When Defining Functions.
Using Optional Arguments
The initializer of
CumulativePowerFactory takes two optional arguments,
start. The first argument holds the exponent that you’ll use to compute a series of powers. It defaults to
2, which is a commonly used value when it comes to computing powers.
The star or asterisk symbol (
exponent means that
start is a keyword-only argument. To pass a value to a keyword-only argument, you need to use the argument’s name explicitly. In other words, to set
value, you need to explicitly type
start argument holds the initial value to compute the cumulative sum of powers. It defaults to
0, which is the appropriate value for those cases in which you don’t have a previously computed value to initialize the cumulative sum.
The special method
.__call__() turns the instances of
CumulativePowerFactory into callable objects. In other words, you can call the instances of
CumulativePowerFactory like you call any regular function. Inside
.__call__(), you first compute the power of
base raised to
Then you add the resulting value to the current value of
.total. Finally, you return the computed power. To give this class a try, open a Python interactive session in a directory containing
power.py and run the code seen on-screen.
These examples show how
CumulativePowerFactory simulates multiple constructors. The first constructor doesn’t take arguments, and it allows you to create class instances that compute powers of
2, which is the default value of the
.total instance attribute holds the cumulative sum of computed powers as you go. The second example shows a constructor that takes
exponent as an argument and returns a callable instance that computes cubes. In this case,
.total works in the same way as the first example.
Become a Member to join the conversation.