Some suggestions for reuse and reduction in Python programming

Source: Internet
Author: User
Returning to Basics

Many popular toys are based on such a concept: simple bricks. These simple blocks can be combined in a variety of ways to create new works-sometimes even completely unexpected. The same concept applies to real-life architectural fields, combining basic raw materials to form useful buildings. Mundane materials, technologies and tools simplify the construction of new buildings, and also streamline the training of new people in this area.

The same basic concepts apply to computer program development techniques, including programs written in the Python programming language. This article describes a method for creating a basic artifact (building block) using Python, which can be used to solve more complex problems. These basic components may be small and simple, and may be large and complex. Regardless of the form, the purpose of our game is to define the basic artifacts and then use them to create a masterpiece that belongs to you.
Functions: Encapsulating logic

In the first few articles in this series, you often have to repeatedly enter all of the code, even if it is exactly the same as the previous line of code. The only exception to this requirement is the use of variables: once the contents of the variable are initialized, they can be reused at any time. It is obvious that the popularization of this usage is of great benefit to us.

One of the most popular proverbs describing outstanding programmers is that they are lazy. This does not mean that great programmers don't work hard-they prefer flexible methods of working, and never do the same thing again and again unless absolutely necessary. This also means that before you need to write code, you first consider how to implement reuse. There are many ways to implement reuse in Python, but the simplest technique is to use functions, also known as methods or subroutines.

Like most modern programming languages, Python supports the use of methods to encapsulate a set of statements so that they can be reused if necessary. Listing 1 shows a simple pseudo-code to show you how to write a method in Python.
Listing 1. Defining pseudo-code for a function

def myFunction (optional input data):  initialize any local data  actual statements that does the work  optionally r Eturn any results

As you can see, in Python, the basic component of a function is the wrapper code, which indicates a series of Python statements that will be reused. The function accepts input parameters, and the input parameters are provided within parentheses immediately following the function name (in this case, myFunction). The function can also return a value (more formally, the object), including a Python container such as a tuple.

Before we really start building functions, let's look at some simple but important points about pseudo-code:

    • Note the case of the character used in the function name: Most characters are lowercase, but when you use multiple words to connect to a function name, the first letter of the next word should be capitalized (for example, F in myFunction). This is called camel casing, a technique widely used in Python and other programming languages to make the name of a function easier to read.
    • The program statements in the function definition are indented, and the function body is composed of Python statement blocks, which must also be indented like loops or conditional statements.
    • The first line of the function definition is also called the method signature (signature), which begins with Def (DEF is the abbreviation for the word define).
    • The method signature ends with a colon, indicating that the following line of code is the body of the function.

At this point, you may have recognized the benefits of using the method. So let's put it in and start writing the function. A For loop is used to create the multiplication table in Discover python, part 6:programming in Python, for the fun of it. Listing 2 shows the same concept, but this example creates a function that encapsulates the logic behind the multiplication table calculation.
Listing 2. First function

>>> def timestable ():   ... For row in range (1, 6): ...     For Col in range (1, 6): ...       Print "%3d"% (row * col),...     Print ... >>> timestable () 1  2  3  4  5 2 4  6  8  ten  3  6  9  4 8 (  5)  >> > t = timestable>>> type (t)
 
  
   
  >>> t
  
   
    
   >>> t () 1  2  3  4  5  2  4  6  8  ten  3  6  9  4 8  5 in  ten
  
   
 
  

The Timestable function is very simple to define, it does not accept any input parameters, and does not return any results. The function body is almost identical to the statement in "Discover Python, Part 6" (but the multiplication table in the article is from 1 to 10). To invoke the method and make it work, simply enter the function name followed by parentheses. In this example, the multiplication table is also output.

In Python, a function is a class of objects, the same as an integer variable and a container object. Thus, you can assign a function to a variable (remember that the variable is dynamically typed in Python). In Listing 2, we assign the Timestable function to the variable T. The next two lines of code indicate that the variable t does point to the function. Finally, we call the Timestable function with the variable T.
Functions: Dynamic Change logic

The Timestable function in Listing 2 is not complex, but is not particularly useful. A more useful example allows you to specify the number of rows and columns to use to generate the multiplication table-in other words, allows you to dynamically change the way a function is manipulated when the function is called. This can be done using two input parameters in the function definition, as shown in Listing 3.
Listing 3. A better multiplication table function

>>> def timesTable2 (nrows=5, ncols=5): ...   For row in range (1, nrows + 1): ...     for cols in range (1, Ncols + 1): ...       Print "%3d"% (row * cols),...     Print ... >>> timesTable2 (4, 6) 1  2  3  4  5  6  2  4  6 8-  12  3  6  9  4  8  >>> TimesTable2 ()   1  2  3  4  5  2  4  6  8  ten  3  6  9  4 8 (  5)  >>> TimesTable2 (ncols=3) 1  2  3  2  4  6  3  6  9  4  8  5  Ten  15

The definitions of the two multiplication table functions are very similar, but the functions in Listing 3 are much more useful (as you can see from the 3 calls in Listing 3). Adding this additional functionality to a function is straightforward: provide two input parameters named Nrows and Ncols, allowing you to change the size of the multiplication table when the function is called. These two parameters are then supplied to the two for loops that generate the multiplication table.

Another important point about the TimesTable2 function is that the two input parameters have default values. Provide a default value for the parameter in the function signature by adding an equal sign and a value after the parameter name, such as Nrows=5. The default parameter gives the program more flexibility because when you call a function, you can include two input parameters, or you can include only one input parameter, or even one parameter. But this approach may cause some problems. If you do not specify all parameters during a function call, you must explicitly write out the name of the parameter you specified so that the Python interpreter can correctly invoke the function. The last function call is a manifestation of this, and it explicitly invokes the TimesTable2 function with ncols=3, which creates a multiplication table of 5 rows (the default) 3 columns (the values provided).
Functions: Returning data

When using a method, the most desirable result is not always the multiplication table. You may want to complete the calculation once and return the computed result value to the calling code. Sometimes to achieve these two purposes, call methods (subroutines) and return values (functions) that do not return any data need to be called separately. In Python, however, you don't have to worry about these semantic issues because you can achieve these two purposes in almost the same way by using the return statement (see Listing 4).
Listing 4. Returns a value in a function

>>> def stats (data):   ... sum = 0.0   ... For value in data:     ... Sum + = value ...   Return (Sum/len (data)) ... >>> stats ([1, 2, 3, 4, 5])   # Find The mean value from a list3.0>>> stats (( 1, 2, 3, 4, 5)   # Find The mean value from a tuple3.0>>> stats () Traceback (most recent call last): File "
  
   
    
  ", line 1, in? Typeerror:stats () takes exactly 1 argument (0 given) >>> stats ("12345") Traceback (most recent call last): File " c9/>
    
     
   ", line 1, in? File "
   
     
      
    ", line 4, in statstypeerror:unsupported operand type (s) for + =: ' float ' and '
   str
     ' 
     
    
 
   
  

This simple function iterates through data (assuming that data is a Python container that holds numeric data), calculates the average of a set of values, and then returns the value. The function definition accepts an input parameter. The average value is passed back through the return statement. When you call a function with a list or tuple that contains numbers 1 through 5, the return value is displayed on the screen. If you call a function without any parameters, a function with a non-container data type, or a function with a container containing non-numeric data, an error occurs. (It is meaningful to throw an error in such cases.) A more advanced approach should include proper error checking and handling to address these situations, but this is beyond the scope of this article. )

This example is already useful, but it can also make it more powerful, as shown in Listing 5. In Python, a function can return any valid object type, including the container type. Therefore, you can calculate multiple quantities and easily return multiple results to the calling statement.
Listing 5. Return compound value

>>> def stats (data):   ... sum = 0.0   ... For value in data:     ... Sum + = value ...   mean = Sum/len (data)   ... sum = 0.0   ... For value in data:     ... Sum + = (value-mean) **2   ... Variance = sum/(len (data)-1)   ... Return (mean, variance) ...>>> stats ([1, 2, 3, 4, 5]) (3.0, 2.5) >>> (M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8 , 9]) >>> print m, v5.0 7.5

To return multiple values from a function, enclose them in parentheses and separate them with commas-in other words, create and return a tuple. The function body of the new stats function is modified to calculate the sample variance of the sequence of numbers. Finally, as shown in the two invocations of the stats function, the tuple value can be accessed as a tuple, or it can be unpacked into its own component.

Modules: Simplifying code reuse

At this point, you may have trusted the value of code reuse. But even with a function, you still need to reenter the function body when you intend to use the function. For example, when you open a new Python interpreter, you must type all the functions that you created earlier. Fortunately, you can use modules to encapsulate related functions (and other Python objects) together, save them in a file, and then import these defined functions into the new Python code, contained within the Python interpreter.

To introduce the method of using modules in Python, we will reuse the stats method in Listing 5. There are two options: You can extract a file named test.py from the compressed file associated with this article, or you can type a function in the editor and save the file as test.py. After you complete the previous step, start a new Python interpreter in the directory where you saved the test.py, and then enter the statement shown in Listing 6.
Listing 6. Using modules

>>> Import test>>> Test.stats ([1, 2, 3, 4, 5, 6, 7, 8, 9]) (5.0, 7.5) >>> from test import stats& Gt;>> (M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> print m, v5.0 7.5

The first line of import test opens the file test.py and processes each statement in the file. Only the stats function is defined here, but you can also define more functions if you want. When calling the stats function, the module name test should be used as the function prefix. The use of this complex name is due to scope considerations, which represent the valid range of names within a program. To tell Python which stats method you want to invoke, you must provide the full name. This is important because you may have more than one object with the same name. Scope rules help Python determine which object you want to use.

The third line from test import stats also opens the file test.py, but it implicitly puts the stats method in the scope of the current file so that you can call the stats function directly (without using the module name). Wisely use the From ... import ... Syntax can make your program more concise, but excessive use can also lead to confusion and even worse scope conflict errors. Don't abuse your new weapon!
Module Library

One of the main benefits of using the Python programming language is the large, built-in standard library that can be accessed as a Python module. Examples of common modules are:

    • Math contains useful mathematical functions.
    • SYS contains data and methods for interacting with the Python interpreter.
    • The array contains the data types of the arrays and related functions.
    • DateTime contains useful date and time-processing functions.

Since these are built-in modules, you can use the Help interpreter to learn more about the content, as shown in Listing 7.
Listing 7. Get Help on the math module

>>> Help (Math) Traceback (recent): File "
 
  
   
  ", line 1, in? Nameerror:name ' math ' isn't defined>>> import math   # need to import Math module in order to use it>>& Gt Help (Math) Help on module math:name  mathfile  /system/library/frameworks/python.framework/versions/2.4/lib/ Python2.4/lib-dynload/math.sodescription This module was always  available. It provides access to the  mathematical functions defined by the C standard. FUNCTIONS  ACOs (...)    ACOs (x)        Return The arc cosine (measured in radians) of X.    ASIN (...)    ASIN (x)        Return the arc sine (measured in radians) of x
 
   ....

The help output of the math module shows a number of supported mathematical functions, including the SQRT function. You can use this function to convert your sample variance calculation to a sample standard deviation calculation, as shown in Listing 8.
Listing 8. Using multiple modules

>>> from math import sqrt>>> from test import stats>>> (M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> print m, sqrt (v) 5.0 2.73861278753

As you can see, you could import multiple modules into a Python program. With the help of a large, built-in module library and a larger number of common libraries, many of which are open source, you will soon become a lazy--and outstanding--programmer.

Executable file

When you import a module, the Python interpreter processes the rows within the module file. In fact, you can call the Python interpreter to process only one Python program that is contained in a file. In UNIX-based? Operating system, you can easily create executable files, as shown in Listing 9.
Listing 9. A complete Python program

#!/usr/bin/env pythondef Stats (data):  sum = 0.0 for  value in data:    sum + = value  mean = Sum/len (data)  sum = 0  for value in data:    sum + = (value-mean) **2  variance = sum/(len (data)-1)  return (mean, variance) ( M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9]) print "The mean and variance of the values" \ "from 1 to 9 inclusive is", M, V

Looking at the example above, you should have a good feeling, putting the Python program inside the file and making it run so simple. The only difference between this example and the code in the test.py file is that it contains the first line. In UNIX-based operating systems, the bank causes the Python interpreter to start automatically and to process the statements in the file before terminating. The other rows in this example define the stats function, call the function, and output the result.

To run the statements in this file, you need to start a Python interpreter and let it read and manipulate the contents of the file. To do this, you must first enter the example in Listing 9 into a file named mystats.py, or you can extract the file from the compressed file associated with this article. Go to the directory that contains the file, and then follow the command shown in Listing 10. Note for Microsoft? Windows? Operating system, only the first command should be used; Other commands are for UNIX systems such as Linux? or Mac OS X) is used.
Listing 10. Execute Python Program

rb% python mystats.pythe mean and variance of the values from 1 to 9 inclusive is 5.0 7.5rb% chmod +x mystats.pyrb%./mys Tats.pythe mean and variance of the values from 1 to 9 inclusive is 5.0 7.5

The command in Listing 10 shows how to run a Python program that is contained in a file. The first command invokes the Python interpreter with the file name, which works regardless of which system is used to install Python, which directory the Python interpreter is located in. The second command chmod the file containing the Python program into an executable file. The third command tells the operating system to run the program. This is achieved by using the Env program, an operating system-independent technique for locating and running programs-in this case, the Python interpreter.

Reuse and reduction

This article describes how to write reusable code in Python. Discusses how to use methods or reusable blocks in a Python program. Method can accept input parameters or return data, including container data types. This functionality makes the approach a powerful way to handle a large number of problems. This article also describes the modules that enable you to merge related methods and data into an organized hierarchy, which can be easily reused in other Python programs. Finally, it describes how to group all of these things together to create a fully functional, stand-alone Python program. As you've seen, the reuse of code means your workload is shrinking. For programmers, laziness is an advantage rather than a bad habit.

  • 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.