A summary of several Python function method design principles

Source: Internet
Author: User
Tags value of pi in python

This article mainly introduces the summary of several Python function method design principles, this article explained that each function to do only one thing, keep simple, keep short, input parameters, output using return statements, etc., the need for friends can refer to the

In any programming language, the application of a function is mainly in the following two situations:

1. code block Repeat, this time must consider the use of functions, reduce the redundancy of the program

2. code block complex, this time you can consider the use of functions to enhance the readability of the program

When the process is complex enough, consider the function and how to combine the functions. In Python to do function design, mainly consider the function size, aggregation, coupling of three aspects, these three should be due to the scope of planning and design. High cohesion and low coupling are the general principles of any language function design.

1. How to break down tasks into more targeted functions, resulting in a convergence

2. How to design communication between functions is also related to coupling

3. How to design the size of the function to enhance its polymerization and reduce its coupling

Polymerization

Each function only does one thing

Perfect program design, each function should and only need to do one thing.

For example: Put an elephant in the fridge in three steps: Open the door, put the elephant in, and close the door.

So you should write three functions instead of a function to do all the things. This structure is clear, the level is clear, good understanding!

Size

Keep it simple and keep it short

Python is a process-oriented language and an object-oriented language, but more of a role in scripting languages.

The same function, using Python to implement its code length may be 1/3 of C/c++/java and other languages. Hundreds of lines of code can achieve a very small function!

If a function that you design in your project needs to be read by the page, consider splitting the function.

Of the more than 200 modules that Python brings, it's rare to see a function that has two or three pages.

Python code is known for simplicity, a function that is too long or has deep nesting is often a symptom of design flaws.

Coupling

Enter use parameters, output use return statement

Doing so allows the function to be independent of what is outside it. Parameters and return statements are the best way to isolate external dependencies.

Use global variables with caution

The first consideration: Global variables are usually a way of communicating between crappy functions.

It raises dependencies and timing problems, which can lead to difficulty in debugging and modifying the program.

Second consideration: from Code and performance optimization, local variables are much faster than global variables.

According to Python's search order for variables: local function variable = = "upper function variable = =" global variable = = "Built-in variable

As you can see from above, local variables are searched first, and once found, stop. The following tests are specifically done, and the results are as follows:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The >" and "M". Port profile   A = 5   def param_test (): B = 5 Res = 0 to I in range (100000000): res = B + I return res   If __name__== ' __main__ ': Profile.run (' Param_test () ") >>> ===================================== RESTART = = ================================= >>> 5 function calls in 37.012 seconds #全局变量测试结果: 37 sec     Ordered by: Standard name     ncalls tottime percall cumtime percall Filename:lineno (function) 1 19.586 19.586 19.586 19.58 6:0 (range) 1 1.358 1.358 1.358 1.358:0 (setprofile) 1 0.004 0.004 35.448 35.448 <string>:1 (<module>) 1 15.857 15.857 35.443 35.443 learn.py:5 (param_test) 1 0.206 0.206 37.012 37.012 profile:0 (param_test ()) 0 0.000 0.000 profile:0 (p Rofiler)        >>> ===================================== Restart ===================================== >> > 5 function calls in 11.504 seconds #局部变量测试结果: 11 sec     Ordered by:standard name     Ncalls Totti Me percall cumtime percall filename:lineno (function) 1 3.135 3.135 3.135 3.135:0 (range) 1 0.006 0.006 0.006 0.006:0 (SETP Rofile) 1 0.000 0.000 11.497 11.497 <string>:1 (<module>) 1 8.362 8.362 11.497 11.497 learn.py:5 (param_test) 1 0.000 0.000 11.504 11.504 profile:0 (param_test ()) 0 0.000 0.000 profile:0 (Profiler)

Avoid changing variable type parameters

Python data types such as lists and dictionaries belong to mutable objects. When passed as a parameter to a function, it is sometimes modified like a global variable.

The disadvantage of this is that it enhances the coupling between functions, which causes the function to be too special and unfriendly. Maintenance is also difficult.

Consider using the copy () function and the deepcopy () function in the slice s[:] and the copy module to make a copy, avoiding modifying the Mutable object

Specific reference to this article: Python in the depth of the copy detailed

Avoid directly changing variables in another module

For example, in the b.py file to import a module, a variable pi = 3.14, but b.py want to change it to: Pi = 3.14159, where you do not know the original value of the variable pi is how much. In this case, you might consider using an understandable function name:

?

1 2 3 4 5 6 #模块a. py pi = 3.14 def setpi (new): pi = new return pi

This has the value of the pi you want, and does not change the value of pi in module A.

?

1 2 3 4 Import a PI = A.SETPI (3.14159) Print Pi;a.pi

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.