Example analysis of python dynamic parameter usage

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.