SoFunction
Updated on 2024-11-17

Python function's universal parameter pass parameter details

Let's show the cardinal parameters of a function by a simple example, we will start by writing the simplest function

def test(*args,**kwargs):
print(args,kwargs)

Then define two variables

l = [1,2,3,4]
d = {"a":1,"b":2}

Let's look at the differences between each of the two ways of passing a parameter.

The first way

test(l,d)

If you are using the above method of passing a parameter, then the 2 variables l and d are passed to args, a formal parameter, as the two elements of the args variable, and kwargs is an empty dictionary without any parameters to pass a he

([1, 2, 3, 4], {'a': 1, 'b': 2}) {}

We can see that the list l and the dictionary d are treated as two elements of a tuple

The second way

test(*l,**d)

If the parameter is passed in the above way, then the variable l will be assigned to args and the variable d will be assigned to kwargs

(1, 2, 3, 4) {'a': 1, 'b': 2}

Through the above demonstration, you should basically understand python's universal parameters, and know how you should pass parameters if the function uses universal parameters.

Got confused today and combed through the universal parameters again

Let's take a look at this function

def foo(action=None,**kwargs):
  print("action",action,sep="=================>")
  print("kwargs", kwargs, sep="=================>")
 
d = {"a":1,"b":2} 
foo(d)
print("=".center(100,"*"))
 
foo(**d)

The result of my implementation is as follows

Let me explain.

The first way to call a function, a dictionary is passed in, which is passed in as a whole, and this dictionary is assigned to the position change, which is the action

The second way to call the function, passing it in via the **dictionary method, he actually passes it in like this a=1, b=2 so it's actually a named variable, and the names of these 2 variables don't ACTION, so the result of the second way to call it would be

action is none

kwargs is a dictionary

Let's take a look at the third method of invocation

d = {"action":"action","a":1}
foo(**d)

Here's a look at the results to see if it makes a little more sense

This is the whole content of this article.