Python Advanced - the Use of Closures

Python advanced - the use of closures Introduction:

Python advanced - the use of closures.Define an external function to receive different configuration information parameters. The parameter is a person's name. Define an internal function to receive dialogue information parameters. In the internal function, the configuration information and dialogue information are spliced and output.

1. Python advanced - the use of closures Case


Requirement: Use closures to implement dialogue information for different people according to configuration information, such as dialogue:
Zhang San: Have you arrived in Beijing? Li Si: We have already arrived. Don't worry.


2. Python advanced - the use of closures Implementation step description


1.Define an external function to receive different configuration information parameters, the parameter is the name of the person
2.Define an internal function to receive dialog information parameters
3.In the internal function, the configuration information and dialog information are spliced and output

3.Python advanced - the use of closures Implementation of function code


# external function
def config_name (name):
# inner function
def say_info (info):
print( name + ": " + info)
return say_info
tom = config_name ("Tom")
tom("Hello!")
tom("Hello, are you there?")
jerry = config_name ("jerry")
jerry("Not here, don't play with me!")
operation result:
Tom: Hello!
Tom: Hello, are you there?
jerry: No, no and play!
Closure case description:
•Closures can also improve code reusability, eliminating the need to manually define additional functions.

4. Summary
•Closures not only save variables from outer functions but also improve reusable lines of code.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00