Python dynamic parameter usage instance analysis and python dynamic instance analysis
This example describes how to use python dynamic parameters. Share it with you for your reference. The specific analysis is as follows:
Let's take a look at a piece of code:
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 variable parameters:
A parameter starting with an asterisk (*) represents an array of any length and can receive a continuous string of parameters. For example, if the preceding Code uploads 1, 2, 3, you can add more parameters.
A parameter that starts with two "*" represents a dictionary. The parameter format is "key = value". It accepts any number of consecutive parameters.
In the function, we can treat the former as a tuple, and the printed result can be seen as a tuple. Note that the call method is an indefinite parameter length, and the length is fixed during method execution, so it is a tuples. At the same time, we can treat the latter as a dictionary.
In the sample code, the variable length parameter is used to customize a class attribute. For a Person class, you can pass in a dictionary type parameter to make this class have more attributes that do not exist, the exec method is used for implementation. Currently, only string parameters can be used. Here we only show the use of variable parameters and the magic power of exec. A real function should not allow any user to customize attributes. The variable parameter number is used to facilitate the definition of a function and make it easier to input parameters when calling a function.
I hope this article will help you with Python programming.