A case study 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:

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.

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.