Talk about using Python built in function getattr to realize distribution mode

  • 2020-07-21 08:56:37
  • OfStack

This article focuses on issues related to the implementation of the distribution pattern using the Python built-in function getattr, which is described below.

The common usage pattern for getattr is as a distributor. For example, if you have a program that outputs data in different formats, you can define the format output function for each output format and then use the format output function required by the distribution function call of only 1.

For example, let's say you have a program that prints site statistics in HTML, XML, and plain text. The output format is specified on the command line or is saved in a configuration file. The statsout module defines three functions: output_html , output_xml and output_text . Then the main program defines the only output function of 1, as follows:


import statsout

def output(data, format="text"):               
  output_function = getattr(statsout, "output_%s" % format) 
  return output_function(data)     

The output function accepts 1 required parameter data and 1 optional parameter format. If the format parameter is not specified, the default value is text and the call to the plain text output function is completed.

You can connect the format parameter value to "output_" to create a function name as the parameter value and then retrieve the function from the statsout module. This approach allows future extensions to easily support other output formats without modifying the distribution function. All you have to do is add one function to statsout, such as output_pdf, and then simply pass "pdf" to the output function as the parameter value of format.

Now you can simply call the output function just like any other function 1. output_function A variable is a reference to the corresponding function in the statsout module.

Did you find an Bug from the previous example? That is, loose coupling between strings and functions without error checking. What happens if the user passes in a format parameter, but the corresponding format output function is not defined in statsout? Fortunately, getattr returns None, which replaces a valid function and is assigned to output_function , then the statement that calls the function on the next line will fail and throw an exception. This is not a good way. Thankfully, getattr is able to use an optional third parameter, a default return value.

conclusion

This is the article on the use of Python built-in function getattr to achieve the distribution mode of all content, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: