Familiar with the coding rules of functions in the legend of Python

Source: Internet
Author: User
When using a function, we should first consider it at the object level. it is not a special thing. although we have used a lot of space to talk about it, it is still an object. There are always a few things about functions. Below are some notes for writing functions. In particular, I did not summarize these issues. I copied them from a book named "Learning Python" and wrote them in Chinese by the way. of course, it is translated from your own perspective and contains some of your own points of view. It can also be understood as a result of Learning Python, but it is a little different.
• Functions are independent. That is to say, do not have too strong coupling. Functions must be independent from external objects. Parameters and return statements are the best way to achieve this independence.
• Do not use global variables as much as possible, which is also a method that gives functions a low coupling degree. Although the global variable implements internal and external function communication, it enhances the external dependency of the function, and often makes function modification and program debugging more troublesome.
• If the object of a parameter is variable data type, do not modify it in the function. Of course, more often, it is better to input parameters that are not changeable.
• The functions and objectives of function implementation must be single. Each function must start with a short sentence to describe the functions and objectives of the function.
• The function should not be too large, but be small. according to the previous principle, the number of code lines will be small if the function has a single purpose. If it feels a little big, you can see whether it can be split into several functions.
• Do not modify the variables in another module file. This is the same as above, with the aim of reducing coupling.

Test recursion

I am cautious about using recursion in python. why? On the one hand, I am afraid that I will not be able to learn it well. In addition, recursion not only consumes resources, but is also faster than for loop.

However, as a programmer, recursion still needs to be understood. Here is a simple example.

The code is as follows:


>>> Def newsum (lst ):
... If not lst:
... Return 0
... Else:
... Return lst [0] + newsum (lst [1:])
...
>>> Newsum ([1, 2, 3])
6

This is a function that calculates the list. (you may have thought of it. isn't there a sum built-in function in python to sum the list? Why do I need to write it myself? Yes, in actual programming, there is no need to write it by yourself. you can use sum. Here we use this example to demonstrate recursion without the significance of programming practice.) of course, I have not determined whether the parameter passed to the function is a list composed of digits, if the letters in the input list are written as follows:

The code is as follows:


>>> Newsum ([1, 2, 3, 'Q'])
Traceback (most recent call last ):
File" ", Line 1, in
File" ", Line 5, in newsum
File" ", Line 5, in newsum
File" ", Line 5, in newsum
File" ", Line 5, in newsum
TypeError: cannot concatenate 'str' and 'int' objects

This is the shortcoming of this function. However, in order to illustrate recursion, we will not be able to care so much. Ignore this defect for the moment. Note that the preceding function contains the return lst (0) + newsum (lst [1:]). in this sentence, one function itself is called. By the way, this is recursive and calls the function itself in the function. Of course, the difference is that the input parameters have changed. To clear the function call process, we can print the parameters passed in each time:

The code is as follows:


>>> Def newsum (lst ):
... Print lst
... If not lst:
... Return 0
... Else:
... Return lst [0] + newsum (lst [1:])
...
>>> Newsum ([1, 2, 3])
[1, 2, 3]
[2, 3]
[3]
[]
6


This is recursion.

In fact, the reader may have thought that even if sum is not used, you can use for to perform the preceding operations.

The code is as follows:


>>> Lst = [1, 2, 3]
>>> Sum_result = 0
>>> For x in lst: sum_result + = x
...
>>> Sum_result
6

Note: functions are objects.

I still remember that when I learned the first part, I kept emphasizing that the variable has no type and the data has a type. at that time, the data encountered included strings, values, lists, tuples, dictionaries, and files, these things are regarded as objects. Functions are similar to them and are also objects. Therefore, you can assign values, pass values to other functions, embed values into data structures, return values from one function to another, and perform other object-oriented operations like the previous objects. Of course, the function object also has a special feature, that is, it can be called by list parameters in parentheses after a function expression.

The code is as follows:


>>> Def newsum (lst): # This recursive function is used as an example.
... Print lst
... If not lst:
... Return 0
... Else:
... Return lst [0] + newsum (lst [1:])
...

>>> Lst = [1, 2, 3]

>>> Newsum (lst) # This is a common method
[1, 2, 3]
[2, 3]
[3]
[]
6
>>> Recusion_fun = newsum # The value assignment statement allows the variable recusion_fun to reference the newsum (lst) object.
>>> Recusion_fun (lst) # The variable can implement operations that are equivalent to function calls.
[1, 2, 3]
[2, 3]
[3]
[]
6


Let's look at another example. In this example, you must remember that a function is an object. I remember it? In list, it can accommodate any object. can it accommodate a function?

The code is as follows:


>>> Fun_list = [(newsum, [1, 2, 3]), (newsum, [1, 2, 3, 5])]
>>> For fun, arg in fun_list:
... Fun (arg)
...
[1, 2, 3]
[2, 3]
[3]
[]
6
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
15

Functions are really objects.

Since it is an object, you can use the dir (object) method to view the relevant information:

The code is as follows:


>>> Dir (newsum)
['_ Call _', '_ class _', '_ closure _', '_ code __', '_ ULTS _', '_ delattr _', '_ dict _', '_ doc _', '_ format __', '_ get _', '_ getattribute _', '_ globals _', '_ hash _', '_ init __', '_ module _', '_ name _', '_ new _', '_ reduce _', '_ performance_ex __', '_ repr _', '_ setattr _', '_ sizeof _', '_ str _', '_ subclasshook __', 'func _ closure ', 'func _ code', 'func _ defaults', 'func _ dict', 'func _ Doc', 'func _ globals ', 'func_name']
>>> Dir (newsum. _ code __)
['_ Class _', '_ cmp _', '_ delattr _', '_ doc __', '_ eq _', '_ format _', '_ ge _', '_ getattribute _', '_ gt __', '_ hash _', '_ init _', '_ le _', '_ lt _', '_ ne __', '_ new _', '_ reduce _', '_ performance_ex _', '_ repr _', '_ setattr __', '_ sizeof _', '_ str _', '_ subclasshook _', 'co _ argcount ', 'co _ cellvars ', 'co _ code', 'co _ consts ', 'co _ filename', 'co _ firstlineno', 'co _ flags ', 'co _ freevars ', 'co _ lnotab', 'co _ name', 'co _ names', 'co _ nlocals', 'co _ stacksize', 'co _ varnames']
>>> Newsum. _ code _. _ doc __
'Code (argcount, nlocals, stacksize, flags, codestring, constants, names, \ n varnames, filename, name, firstlineno, lnotab [, freevars [, cellvars]) \ n \ nCreate a code object. not for the faint of heart.'
>>> Newsum. _ code _. co_varnames
('Lst ',)
>>> Newsum. _ code _. co_argcount
1

Therefore, when using a function, you should first consider it at the object level. it is not a special thing, although we have used a lot of space to talk about it, but it is still an object.

Related Article

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.