Home > Article > Backend Development > Python implements a function that accepts any number of parameters
The following is a Python implementation of a function method that accepts any number of parameters. It has a good reference value and I hope it will be helpful to everyone. Let's come and take a look.
This function is not a function that I urgently need, but I just happened to see it and thought I might use it in the future. The function is to implement the function to accept different numbers of parameters.
In fact, this function is familiar in C language, although the implementation form is different. The main function in C language can implement similar functions. In this way, a program that supports command line parameters can be implemented.
First write a python demonstration code to implement the corresponding function:
defFuncDemo(*par): print("number of pars: %d" %len(par)) print("type of par: %s" %type(par)) i = 0 if len(par) != 0: for p in par: i = i + 1 print("%d par is:%s" %(i,p))
Run the test interaction record after loading:
>>>FuncDemo() number of pars: 0 type of par:<class 'tuple'> >>>FuncDemo(1,2,3) number of pars: 3 type of par:<class 'tuple'> 1 par is: 1 2 par is: 2 3 par is: 3 >>>FuncDemo(1,2,3,'abc') number of pars: 4 type of par:<class 'tuple'> 1 par is: 1 2 par is: 2 3 par is: 3 4 par is: abc
This is basically the method and application of Python to implement functions that accept arbitrary parameters , then summarize the corresponding knowledge.
Implementing a function in Python that accepts any number of parameters is relatively simple in form. Just add an asterisk in front of the parameter so that the corresponding parameter position can accept any number of parameters. The corresponding parameter is a tuple in the function, which can also be seen from the above interaction results.
In fact, this function can also support the passing of a dictionary. If a dictionary is passed in, then pairs of parameters need to be passed in.
For the time being, this function is not very useful in my work and life. Let’s see how effective it is as a backup function!
Related recommendations:
Python implementation of finding the longest non-repeating substring for a given string
The above is the detailed content of Python implements a function that accepts any number of parameters. For more information, please follow other related articles on the PHP Chinese website!