class Frame(Widget):
def __init__(self, master=None, cnf={}, **kw):
what is the meaning of **kw in this function, and what does it represent?
class Frame(Widget):
def __init__(self, master=None, cnf={}, **kw):
what is the meaning of **kw in this function, and what does it represent?
This is sort of buried in the language reference. If you look here: Click Here, it gets explained, but you have to dig. In particular:
or passed as a value in a dictionary preceded by **
That means that the identifier after the "**" is a dictionary with "variable name: value" entries.
The key word argument **kw indicates a dictionary of variable number of key:val arguments
Used when the number of arguments is not known ahead of time, an example ...
def make_dic(**kw):
print(vars()) # show local dictionary
return kw
d = make_dic(dg='dog', bw='bow', ct='cat')
print('-'*50)
print(d)
''' result ...
{'kw': {'dg': 'dog', 'bw': 'bow', 'ct': 'cat'}}
--------------------------------------------------
{'dg': 'dog', 'bw': 'bow', 'ct': 'cat'}
'''
A little more about *args
and **kwargs
First vehicle
take only 'car'
as agument.
Next *args
take 'hello', 'world'
and make it a tuple.
Next **kwargs
take key_a='value 1', key_b='value 2'
and make it a dictionary.
def func(vehicle, *args, **kwargs):
#argument vehicle
print(vehicle) #--> car
#argument *args
print(args) #--> ('hello', 'world')
print(args[1]) #--> world
#argument **kwargs
print(kwargs) #--> {'key_b': 'value 2', 'key_a': 'value 1'}
print(kwargs['key_a']) #--> value 1
func('car', 'hello', 'world', key_a='value 1', key_b='value 2')
*args
can take many arguments.
def bar(*args):
print(sum(args)) #--> 45
bar(1,2,3,4,5,6,7,8,9)
**kwargs
can take many arguments.
So here iterate over dictionary and print key --> value.
def foo(**kwargs):
for key in kwargs:
print("Values from dict--> {}: {}".format(key, kwargs[key]))
foo(Name='Zara', Age=7, Class='first')
"""Output-->
Values from dict--> Age: 7
Values from dict--> Name: Zara
Values from dict--> Class: first
"""
Thanks guy for the indept explanation.
in short:
arg = is used to pass in an argument on size 1
*arg = is used to pass in argument of any size more than 0
**arg = is used to pass in a dict of size more than 0
thanks once again
by the way @snippsat i love your 3d works they are nice
I don't if I'd think about them in terms of sizes...
arg = required arguments of the function. Function will error without them.
*args = Additional non-keyword arguments that are not required for function to run.
**kwargs = additional keyword arguments that are not required.
*args and **kwargs are options.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.