|
| 1 | +""" |
| 2 | +from class notes session 6: |
| 3 | +
|
| 4 | +Function arguments in variables |
| 5 | +function arguments are really just |
| 6 | +
|
| 7 | +a tuple (positional arguments) |
| 8 | +a dict (keyword arguments) |
| 9 | +def f(x, y, w=0, h=0): |
| 10 | + print("position: {}, {} -- shape: {}, {}".format(x, y, w, h)) |
| 11 | +
|
| 12 | +position = (3,4) |
| 13 | +size = {'h': 10, 'w': 20} |
| 14 | +
|
| 15 | +!!!!!!!!!!!!!!!!!!!! notice the * and ** below : one * for tuple items, and ** for values from a dictionary !!!!!!! |
| 16 | +
|
| 17 | +>>> f(*position, **size) |
| 18 | +position: 3, 4 -- shape: 20, 10 |
| 19 | +Function parameters in variables |
| 20 | +You can also pull the parameters out in the function as a tuple and a dict: |
| 21 | +
|
| 22 | +def f(*args, **kwargs): |
| 23 | + print("the positional arguments are:", args) |
| 24 | + print("the keyword arguments are:", kwargs) |
| 25 | +
|
| 26 | +In [389]: f(2, 3, this=5, that=7) |
| 27 | +the positional arguments are: (2, 3) |
| 28 | +the keyword arguments are: {'this': 5, 'that': 7} |
| 29 | +This can be very powerful... |
| 30 | +
|
| 31 | +Passing a dict to str.format() |
| 32 | +Now that you know that keyword args are really a dict, you know how this nifty trick works: |
| 33 | +
|
| 34 | +The string format() method takes keyword arguments: |
| 35 | +
|
| 36 | +In [24]: "My name is {first} {last}".format(last="Barker", first="Chris") |
| 37 | +Out[24]: 'My name is Chris Barker' |
| 38 | +Build a dict of the keys and values: |
| 39 | +
|
| 40 | +In [25]: d = {"last":"Barker", "first":"Chris"} |
| 41 | +And pass to format()``with ``** |
| 42 | +
|
| 43 | +In [26]: "My name is {first} {last}".format(**d) |
| 44 | +Out[26]: 'My name is Chris Barker' |
| 45 | +
|
| 46 | +""" |
0 commit comments