Suggestions on reuse and reduction in Python Programming

Source: Internet
Author: User
Tags asin
This article mainly introduces some suggestions for reuse and reduction in Python programming, from the IBM official technical documentation. For more information, see Back to nature

Many popular toys are based on the concept of simple building blocks. These simple building blocks can be combined in multiple ways to create new works-sometimes even completely unexpected. This concept also applies to the construction field in real life, combining basic raw materials to form useful buildings. Ordinary materials, technologies, and tools simplify the construction of new buildings, and also simplify the training of new personnel entering this field.

The same basic concepts also apply to computer programming technologies, including programs written in Python programming languages. This article describes how to create a basic component (building block) using Python, which can be used to solve more complex problems. These basic components may be small, simple, and complex. In either form, our game aims to define basic components and then use them to create your masterpiece.
Function: encapsulation logic

In the first few articles of this series, you usually have to repeat all the code, even if it is exactly the same as the previous line of code. The only special case of this requirement is the use of variables: once the content of the variables is 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 sayings about outstanding programmers is that they are very lazy. This does not mean that outstanding programmers do not work hard-they prefer flexible working methods, and never do the same thing repeatedly unless absolutely necessary. This means that you should first consider how to implement reuse before writing code. Python has multiple ways to achieve reuse, but the simplest technique is to use functions, also known as methods or subroutines.

Similar to most modern programming languages, Python supports the use of methods to encapsulate a group of statements so that they can be reused when necessary. Listing 1 provides a simple pseudocode that shows you how to write in Python.
Listing 1. defining pseudo code of a function

def myFunction(optional input data):  initialize any local data  actual statements that do the work  optionally return any results

As you can see, in Python, the basic component of a function is the package code, indicating a series of Python statements that will be reused. The function can accept input parameters. the input parameters are provided in parentheses following the function name (myFunction in this example. Functions can also return values (more formally speaking: objects), including Python containers like tuple.

Before building a function, let's take a look at some simple but important points about pseudo-code:

  • Note that the characters used in the function name are case-sensitive: most characters are in lower case. However, when multiple words are used to connect to a function name, the first letter of each subsequent word should be written in large numbers (for example, F in myFunction ). This is the so-called camel casing. it is a widely used technology in Python and other programming languages that makes the name of a function easier to read.
  • The program statements in the function definition adopt indent layout. the Function body consists of Python statement blocks and must also be indented as a loop or condition statement.
  • The first line of the function definition is also called method signature. it starts with def (def is the abbreviation of define ).
  • The method signature ends with a colon, indicating that the following code line is the function body.

At this point, you may have recognized the advantages of using methods. Let's get involved and start writing functions. "Discover Python, Part 6: Programming in Python, For the fun of it" uses a for loop to create a multiplication table. Listing 2 demonstrates the same concept, but in this example, a function is created to encapsulate the logic behind multiplication table calculation.
Listing 2. the 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  10  3  6  9  12  15  4  8  12  16  20  5  10  15  20  25 >>> t = timesTable>>> type(t)
 
  >>> t
  
   >>> t() 1  2  3  4  5  2  4  6  8  10  3  6  9  12  15  4  8  12  16  20  5  10  15  20  25
  
 

The timesTable function is very simple to define. it does not accept any input parameters or return any results. The function body is almost identical to the statement in "Discover Python, Part 6" (but the multiplication table in this article is from 1 to 10 ). To call a method and make it take effect, you only need to enter the function name and then enclose it in parentheses. In this example, the multiplication table is also output.

In Python, a function is a type of object, which is the same as an integer variable and a container object. Therefore, you can assign a function to a variable (remember that in Python, variables are dynamically typed ). In listing 2, we assign the timesTable function to the variable t. The following two lines of code indicate that the variable t actually points to the function. Finally, we use variable t to call the timesTable function.
Function: dynamically changing the 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 used to generate a multiplication table-in other words, allows you to dynamically change the function operation mode when calling a function. Use two input parameters in the function definition to implement this function, as shown in listing 3.
Listing 3. better multiplication table functions

>>> 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  10  12  3  6  9  12  15  18  4  8  12  16  20  24 >>> timesTable2()   1  2  3  4  5  2  4  6  8  10  3  6  9  12  15  4  8  12  16  20  5  10  15  20  25 >>> timesTable2(ncols=3) 1  2  3  2  4  6  3  6  9  4  8  12  5  10  15

The two multiplication table functions have very similar definitions, but the functions in listing 3 are much more useful (this can be seen through three calls in listing 3 ). The method for adding this function to a function is very simple: two input parameters named nrows and ncols are provided, allowing you to change the size of the multiplication table when calling the function. These two parameters are subsequently provided to the two for loops that generate the multiplication table.

Another important aspect of the timesTable2 function is that two input parameters have default values. Provide the default value for the parameter in the function signature by adding the equal sign and value after the parameter name, for example, nrows = 5. Default parameters give the program more flexibility, because when you call a function, it can contain two input parameters, or only one input parameter, or even one parameter. However, this method may cause some problems. If you do not specify all parameters during the function call, you must explicitly write the name of the parameter you specified so that the Python interpreter can call the function correctly. The last function call explicitly calls the timesTable2 function with ncols = 3. the Function creates five rows (default) the multiplication table of the three columns (provided values.
Function: return data

When using this method, what people want most is not always a multiplication table. You may want to complete a calculation and return the calculation result value to the calling code. To achieve these two goals, you need to call the call methods (subroutines) and return values (functions) that do not return any data respectively ). However, in Python, you do not need to worry about these semantic issues, because the return statement can be used in almost the same way (see listing 4 ).
Listing 4. return a value in the 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 "
  
   ", line 1, in ? File "
   
    ", line 4, in statsTypeError: unsupported operand type(s) for +=: 'float' and 'str'
   
  
 

This simple function traverses data (assume that data is a Python container containing digital data), calculates the average value of a set of data, and then returns the value. The function definition accepts an input parameter. The average value is returned by the return statement. When you call a list or tuple function with numbers 1 to 5, the return value is displayed on the screen. If you call a function without any parameters, a function with non-container data type, or a function with a container containing non-digital data, an error occurs. (In this case, it makes sense to throw an error. More advanced handling methods should include appropriate error checking and handling to cope with these situations, but this is not covered in this article .)

This example is very useful, but can make it more powerful, as shown in listing 5. In Python, a function returns any valid object type, including the container type. Therefore, you can calculate multiple numbers and easily return multiple results to the call statement.
Listing 5. return compound values

>>> 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 a bracket and separate them with commas (,). In other words, create and return a tuple. The new stats function must be slightly modified to calculate the sample variance of the numeric sequence. Finally, as shown in the two calls to the stats function, the tuple value can be accessed as a tuple, or it can be decompressed as its respective components.

Module: simplified code reuse

So far, you may have believed in the value of code reuse. But even if you use a function, you still need to re-enter the function body when you plan to use the function. For example, when you open a new Python interpreter, you must type all the previously created functions. Fortunately, you can use the module to encapsulate related functions (and other Python objects) and save them in a file, then, import the predefined functions into the new Python code, including the Python interpreter.

To introduce how to use modules in Python, we will reuse the stats method in listing 5. There are two options: you can extract the file named test. py from the compressed file related to this article, you can also type a function in the editor, and then save the file as test. py. After completing the preceding step, start a new Python interpreter in the directory where you saved test. py, and enter the statement shown in listing 6.
Listing 6. Modules

>>> import test>>> test.stats([1, 2, 3, 4, 5, 6, 7, 8, 9])(5.0, 7.5)>>> from test import stats>>> (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 stats functions are defined here, but more functions can be defined if needed. When calling the stats function, the module name test should be used as the function prefix. The reason for using this complex name is out of scope. Scope indicates the effective range of the name in a program. To tell Python which stats method you want to call, you must provide the complete name. This is important because you may have multiple objects with the same name. Scope rules can help Python determine the objects you want to use.

The third line from test import stats also opens the file test. py, but it implicitly places the stats method into the scope of the current file, so that you can directly call the stats function (without using the module name ). Wise use of the from... import... syntax can make your program more concise, but excessive use may lead to confusion, and even worse scope conflict errors. Do not abuse your new weapon!
Module library

A major benefit of using the Python programming language is that a large built-in standard library can be accessed as a Python module. Examples of common modules are as follows:

  • Math contains useful mathematical functions.
  • Sys contains the data and methods used to interact with the Python interpreter.
  • Array contains the array data type and related functions.
  • Datetime contains useful date and time processing functions.

Because these are built-in modules, you can use the help interpreter to learn more, as shown in listing 7.
Listing 7. get help information about the math module

>>> help(math)Traceback (most recent call last): File "
 
  ", line 1, in ?NameError: name 'math' is not defined>>> import math   # Need to import math module in order to use it>>> 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 is 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 large number of supported mathematical functions, including sqrt functions. You can use this function to convert your sample variance calculation to 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 can import multiple modules into a Python program. With the help of large, built-in module libraries and a larger number of public libraries (many of which are open source code, you will soon become a lazy-outstanding-programmer.

Executable files

When importing a module, the Python interpreter processes the lines in the module file. In fact, you can call the Python interpreter to process only one Python program contained in a file. In UNIX? In the 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 are ",m, v

In the above example, you should have a bit of a favor, put the Python program in a file, and make it so easy to run. The only difference between this example and the code in the test. py file is that it contains the first line. In a UNIX-based operating system, this line will enable the Python interpreter to automatically start and terminate the statements in the pre-processing files. Other rows in this example define the stats function, call the function, and output the result.

To run the statements in this file, you must start a Python interpreter to read and process the file content. To achieve this, you must first input the example in listing 9 to a file named mystats. py, or extract the file from the compressed file related to this article. Go to the directory that contains the file and run the command in listing 10. Note that for Microsoft? Windows? In the operating system, only the first command should be used. other commands are for UNIX systems (such as Linux? Or Mac OS X.
Listing 10. execute the Python program

rb% python mystats.pyThe mean and variance of the values from 1 to 9 inclusive are 5.0 7.5rb% chmod +x mystats.pyrb% ./mystats.pyThe mean and variance of the values from 1 to 9 inclusive are 5.0 7.5

The command in listing 10 shows how to run a Python program contained in the file. The first command calls the Python interpreter by file name. this method is effective regardless of the system in which the Python and Python interpreter are installed. The second command, chmod, makes the file containing the Python program executable. The third command tells the operating system to run the program. This is implemented by using the env program, which is an operating system-independent technology used to locate and run programs-the Python interpreter in this example.

Reuse and reduction

This article describes how to write reusable code in Python. Discusses how to use methods or reusable blocks in Python programs. The method can accept input parameters or return data, including the container data type. This feature makes the method a powerful way to handle a large number of problems. This article also introduces modules that allow you to merge related methods and data into an organizational hierarchy, which can be easily reused in other Python programs. Finally, we also introduced how to combine all these contents to create a fully functional and independent Python program. As you can see, code reuse reduces your workload. 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.