Let's look at three common reasons for writing internal functions.
1. Closures and Factory Functions
The value in the scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.
def print_msg(msg): """This is the outer enclosing function""" def printer(): """This is the nested function""" print(msg) return printer
Now try calling this function.
>>> another = print_msg("Hello") >>> another() Hello
It's unusual. The print_msg() function was called with the string "Hello" , and the returned function was bound to another . When calling another() message was still remembered, although we had already completed the print_msg() function. This method by which some data ( "Hello" ) is bound to code is called a closure in Python.
When to use closure?
So what are closures for? Closing can avoid using global values and provides hidden, hidden information. It can also provide an object-oriented solution to the problem. When several methods are implemented in a class (one method in most cases), closures can provide alternative and more elegant solutions. Link
2. Encapsulation:
The general concept of encapsulation is to hide and protect the inner world from the External. Here, internal functions can only be accessed inside the external and protected from everything that happens outside the function.
3. Keepin it DRY
Perhaps you have a gigantic function that executes the same pieces of code in many places. For example, you can write a function that processes a file, and you want to accept either an open file object or a file name:
def process(file_name): def do_stuff(file_process): for line in file_process: print(line) if isinstance(file_name, str): with open(file_name, 'r') as f: do_stuff(f) else: do_stuff(file_name)
For more information, you can send this blog.
sujit tiwari Sep 07 '15 at 11:11 2015-09-07 11:11
source share