The examples in this article describe Python dynamic parameter usage. Share to everyone for your reference. The specific analysis is as follows:
Let's look at a piece of code:
?
| 1 2 3 4 5 6 7 8 9 10 11-12 |
Class Person:def __init__ (self,*pros,**attrs): Self.name = "Jeff" Self.pros = Pros for (key,value) in Attrs.items (): STM = "self.%s =/"%s/""% (key,value) EXEC (STM) if __name__ = = "__main__": Jeff = Person (1,2,3,sex= "boy") print Jeff.pros Prin T jeff.sex print dir (Jeff) |
The printed content is:
?
| 1 2 3 |
(1, 2, 3) boy [' __doc__ ', ' __init__ ', ' __module__ ', ' name ', ' Pros ', ' sex '] |
Python Indefinite parameter:
The argument begins with a * number that represents an array of arbitrary lengths that can receive consecutive parameters, such as the 1,2,3 in the code above, and you can do more.
The argument begins with a two * number that represents a dictionary, in the form of "Key=value", which accepts any number of consecutive arguments.
Within a function, we can treat the former as a tuple, and the printed result is a tuple. Note that the calling method is a variable length and is a tuple when the method executes, and the lengths are fixed. At the same time, we can treat the latter as a dictionary.
The example code uses variable-length parameters to implement a personalized customization of a class attribute, and for a person class, you can make the class have more properties that don't exist by passing in the dictionary type of arguments, using the Exec method, which is currently available only through the parameters of the string. Here just shows the use of variable parameters and the magic power of exec. A real function should not allow arbitrary user-defined attributes, the purpose of which is to facilitate the definition of functions and invoke the function, the argument is more free to pass in the form.
I hope this article will help you with your Python programming.