-
[Python] ArgumentsTIL 2022. 6. 6. 17:12
- We need to be careful using mutable default arguments when defining our functions
- The same argument will be called again when doing multiple function calls, resulting in an error
- To avoid this matter, we can use None as a special value to indicate we did not receive anything and instantiate a new empty list
def createStudent(name, age, grades=None): if grades is None: grades = [] return { 'name': name, 'age': age, 'grades': grades } def addGrade(student, grade): student['grades'].append(grade) # To help visualize the grades we have added a print statement print(student['grades'])
*args and **kwargs
We can use *args(non-keyword arguments) and **args(keyword arguments) to define our function parameters
Function arguments are accepted in the following order in the function parameter:
- Standard positional arguments
- *args
- non-keyword arguments / positional arguments in a function call are mapped to an args tuple.
- Standard keyword arguments
- **kwargs
- keyword arguments in a function call are mapped to an args dictionary
- we can use dictionary operations on the keyword arguments
def print_animals(animal1, animal2, *args, animal4, **kwargs): print(animal1, animal2) print(args) print(animal4) print(kwargs)
print_animals('Snake', 'Fish', 'Guinea Pig', 'Owl', animal4='Cat', animal5='Dog') #output #Snake Fish #('Guinea Pig', 'Owl') #Cat #{'animal5': 'Dog'}
def assign_food_items(**order_items): food = order_items.get('food') drinks = order_items.get('drinks') print(food) print(drinks) # Example Call assign_food_items(food='Pancakes, Poached Egg', drinks='Water') #output # Pancakes, Poached Egg # Water
We can apply *args and **args for function calls as well
my_num_list = [3, 6, 9] numbers = {'num1': 3, 'num2': 6, 'num3': 9} def sum(num1, num2, num3): print(num1 + num2 + num3) sum(*my_num_list) sum(**numbers) #output is 18 for both cases
'TIL' 카테고리의 다른 글
[Python] Mutable vs Immutable, DB Key Types, Queryset vs Object (0) 2022.06.15 Web Dev Bootcamp TIL Day-36(Django MySQL: many-many. query & csv -> json) (0) 2022.06.07 Web Dev Bootcamp TIL Day-33 (Django proj. Start & Recommendation Systems ) (0) 2022.06.04 Web Dev Bootcamp TIL Day-32(Django ORM) (0) 2022.05.31 Web Dev Bootcamp TIL Day-31 (Django CRUD) (0) 2022.05.30