Unlimited Keyword Arguments
def calculate(**kwargs):
print(kwargs)
calculate(add=3, multiply=5)
----------------------------------
{'add': 3, 'multiply': 5} => dictionary
def calculate(**kwargs):
for key, value in **kwargs.items():
print(key)
print(value)
calculate(add=3, multiply=5)
----------------------------------
add
3
multiply
5
def calculate(**kwargs):
print(kwargs["add"])
calculate(add=3, multiply=5)
----------------------------------
3
- To refer to our arguments by name rather than by position
- Type(**kwargs) ⇒ dictionary
- This dictionary basically represents each of the keyword arguments and their values.
- kwargs["add"] ⇒ It basically lets me look through all of the inputs and find the ones that I want and use them to do something.
Example
def calculate(n, **kwargs):
n += kwargs["add"]
n *= kwargs["multiply"]
print(n)
calculate(2, add=3, multiply=5)
---------------------------------------
25
- I takes the first value 2 as equal to n, and then n, this 2, is going to be added to the number I wanted to add which is 3, so 2 + 3 is 5.
- Then it multiplied that 5 by whatever it is I had stored in multiply. So 5 plus 5, and we get 25.
Create a class with **kwargs
- This kw are going to be all of the optional arguments that I'll pass in when I'm initializing a new object from this class.
class Car:
def __init__(self, **kw):
#self.make = kw["make"]
#self.model = kw["model"]
self.make = kw.get("make")
self.model = kw.get("model")
self.color = kw.get("color")
self.seats = kw.get("seats")
my_car = Car(make="Nissan", model="GT-R")
print(my_car.make)
print(my_car.model)
print(my_car.color)
print(my_car.seats)
---------
Nissan
GT-R
None
None
- In fact, with dictionaries, we can get hold of the values through the square bracket method, but we can also use a function called get().
- We use get in a very similar way to the way that we use the square brackets. We just pass in the name of the key and we want to get hold of the value.
- The benefit of get() is that if this key doesn't exist in the dictionary, then it will just return none and it won't give us an error.
TKinter