What are ** and * in the parameters?

Asked 1 years ago, Updated 1 years ago, 77 views

What does * and ** attached to param2 do in the code below?

def foo(param1, *param2):
def bar(param1, **param2):

python syntax argument-passing identifier kwargs

2022-09-22 22:31

1 Answers

*args and **kwargs are used to receive more than 0 factors. It's acceptable if you don't get any factors, if you get 10 or 100.

*args stores the parameters of the function as tuple.

def foo(*args):
    for arg in args:
        print arg

print "---foo()---"
foo()

print "\n---foo(1)---"
foo(1)

print "\n---foo(1,2,3,4,5)---"
foo(1,2,3,4,5)

Results:

---foo()---

---foo(1)---
1

---foo(1,2,3,4,5)---
1
2
3
4
5

**kwargs stores keyword argument as a dictionary (except formal parameter).

def foo(keyword=3, **kwargs):
    for key in kwargs:
        print key, kwargs[key]

print "---foo()---"
foo()

print "\n---foo(number = 'one')---"
foo(number = 'one')

print "\n---foo(keyword='1', temp1='hello', temp2='world!')---"
foo(keyword=1, temp1='hello', temp2='world!')

Results:

---foo()---

---foo(number = 'one')---
number one

---foo(keyword='1', temp1='hello', temp2='world!')---
temp2 world!
temp1 hello

*l releases the list as an item when used in the function's factors.

def foo(num1, num2):
    print num1, num2

l = [1,2]
Forward to (1,2) not foo(*l) #([1,2])


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.