I can’t find a definitive answer for this. As far as I know, you can’t have multiple __init__ functions in a Python class. So how do I solve this problem?
Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways of creating cheese objects…
- One that takes a number of holes like this:
parmesan = Cheese(num_holes=15). - And one that takes no arguments and just randomizes the
number_of_holesproperty:gouda = Cheese().
I can think of only one way to do this, but this seems clunky:
class Cheese: def __init__(self, num_holes=0): if num_holes == 0: # Randomize number_of_holes else: number_of_holes = num_holes
What do you say? Is there another way?
Actually
Noneis much better for "magic" values:Now if you want complete freedom of adding more parameters:
To better explain the concept of
*argsand**kwargs(you can actually change these names):http://docs.python.org/reference/expressions.html#calls