xxxxxxxxxx
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', )
xxxxxxxxxx
# Basic syntax:
def your_function(a, b="blargh", *args, **kwargs):
# Where:
# - a is a required argument
# - b is an optional argument with a default. It is set as the string
# "blargh" if omitted
# - *args allows you to pass any number of additional (unnamed) arguments
# which are passed to the function as a tuple
# - **kwargs allows you to specify any number of additional (named) arguments
# which are passed to the function as a dict
# Note, if you use *args, it should come after other arguments (except **kwargs)
# and if you use **kwargs, it should come after all other arguments
# Example usage:
def your_function(a, b="blargh", *args, **kwargs):
print(a, b, args, kwargs)
your_function(1,2,3,4,5, six="6")
--> 1 2 (3, 4, 5) {'six': '6'}
# Note, the second argument, 2, replaces the default of "blargh"
# Note, six="6" is how you pass arguments to kwargs, like a dictionary
xxxxxxxxxx
def my_func(a = 1, b = 2, c = 3):
print(a + b + c)
my_func()
#OUTPUT = 6
my_func(2)
#This changes the value of a to 2
#OUTPUT = 7
my_func(c = 2)
#This changes the value of c to 2
#OUTPUT = 5
xxxxxxxxxx
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f) #prints values of c,d,e,f
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None) #test if 'c' defined
d = kwargs.get('d', None) #otherwise, return None
#etc
myfunc(a,b, c='nick', d='dog', )
#kwargs = dict of all the parameters that are key valued after a,b
xxxxxxxxxx
def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):
#code
xxxxxxxxxx
def to_smash(total_candies, n_friends=3):
return total_candies % n_friends
#Here n_friends is Optional Parameter
xxxxxxxxxx
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
xxxxxxxxxx
def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):
#code