The examples in this article describe Python dynamic parameter usage. Share to everyone for your reference. The specific analysis is as follows:
Take a look at the code first:
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 print jeff.sex print dir (Jeff)
The printed content is:
(1, 2, 3) boy[' __doc__ ', ' __init__ ', ' __module__ ', ' name ', ' Pros ', ' sex ']
Python Indeterminate parameters:
A parameter that begins with an * number represents an array of any length that can receive successive strings of arguments, as in the code above, you can do more.
The argument begins with a two * number that represents a dictionary with the form "Key=value", which accepts any number of consecutive arguments.
Within the 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 parameter, and when the method executes, it is set, so it is a tuple. At the same time, we can treat the latter as a dictionary.
The sample code uses variable-length parameters to personalize a class property, and for a person class, you can make the class have more properties than it originally existed by passing in a parameter of the dictionary type, implemented by using the Exec method, which is currently only available through the string's arguments. This is just a demonstration of the use of variable parameters and the magical power of exec. The real function should not allow any user to customize the properties, the purpose of the variable parameter is to define the function convenient and call the function, the parameter is more free to pass in the form.
Hopefully this article will help you with Python programming.