Python Function Arguments With Default Arguments
Solution 1:
Required arguments must come before default arguments, otherwise python doesn't know which one the value is meant for.
See Dive into python section on default and named arguments.
Solution 2:
When you are passing a value default argument, all arguments to the right of it should also have default values.
This holds true for C++ as well.
Eg:
Validdef example(a = 1, b = 2):pass
Validdef example(a , b = 2):pass
Errordef example(a = 1, b):pass
Solution 3:
As error message says, default arguments should follow non-default ones, like this:
def__init__(self, edate, fdate=""):
self.fdate = fdate
self.edate = edate
Refer to docs where this behaviour is clearly depicted.
Solution 4:
SyntaxError: non-default argument follows default argument
Your default arguments must come later to non default arguments.
The reason: Your interpreter will have a hard time assigning the arguments if you do a mix up. So it doesn't support it and throws a SyntaxError.
Just change it to
def__init__(self, edate, fdate=""):
@Edit1: Few languages like Kotlin allows you to have default args before non-default args. In this case you will be using a named arg to set the function parameters.
Solution 5:
Here is how I would solve it: I would write a small class and two factory functions that call the class constructor and return the result:
classDateRange:def__init__(self, dfrom='', dto=''):
self.dfrom = dfrom
self.dto = dto
defdate_from_to(dfrom, dto):
return DateRange(dfrom, dto)
defdate_to(dto):
return DateRange(dto=dto)
As you have seen from the error message, you can't define a function that behaves the way you want. If you use two functions it's easy enough to document them and to remember how to use them.
Post a Comment for "Python Function Arguments With Default Arguments"