In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the concept and case analysis of closures in Python. The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the concept and case analysis of closures in Python.
The concept of closures in Python:
Let's try to understand closures conceptually. In some languages, when you can (nest) define another function in a function, a closure may occur if the internal function references the variables of the external function. Closures can be used to create relationships between a function and a set of "private" variables. These private variables can maintain their persistence during the process that a given function is called multiple times. To put it simply, when a function is returned as an object, with an external variable, a closure is formed. Examples are as follows:
Def make_printer (msg):
Def printer ():
Print msg # with contraband (external variable)
Returnprinter # returns functions with contraband goods
Printer = make_printer (Foo!)
Printer ()
The meaning of closures in Python:
What's the point of closures? Why do you need closures? The meaning of a closure is that it contains external variables (contraband). If it does not contain contraband, it is no different from an ordinary function. If the same function carries different contraband goods, it will achieve different functions. In fact, you can also understand that closures are very similar to the concept of interface-oriented programming. Closures can be understood as lightweight interface encapsulation. The interface defines a set of constraint rules for method signatures, as shown in the following example.
Deftag (tag_name):
Defadd_tag (content):
Return "{1}" .format (tag_name,content)
Returnadd_tag
Content = Hello
Add_tag = tag (a)
Printadd_tag (content)
# Hello
Add_tag = tag (b)
Printadd_tag (content)
# Hello
In this example, we want a function to add tag to content, but what the tag_name looks like depends on the actual requirements, and the interface for external calls has been determined, that is, add_tag (content). If we implement it in an interface-oriented way, we will first write add_tag as an interface, specify its parameters and return type, and then implement add_tag for an and b, respectively. But in the concept of closures, add_tag is a function that requires two parameters, tag_name and content, except that the parameter tag_name is packaged away. So you can tell me how to pack it in the first place and take it with you.
The above example is not very vivid, in fact, in our life and work, the concept of closure is also very common. For example, when you dial on a mobile phone, you only care about who you call, rather than worrying about how each brand of mobile phone is implemented and which modules are used. For example, if you go to a restaurant, you can enjoy the service as long as you pay for it. You don't know how much gutter oil is used in that table. These can be seen as closures, returning some functions or services (phone calls, meals), but these functions use external variables (antennas, gutter oil, etc.). You can also think of an instance of a class as a close. when you construct this class, you use different parameters, which are the packages in the closure, and the method provided by this class is the function of the closure. But the class is much larger than the closure, because the closure is just a function that can be executed, but class instances are likely to provide a lot of methods.
When to use closures:
In fact, closures are very common in Python, but you haven't noticed that this is a closure. For example, the decorator Decorator in Python, if you need to write a decorator with parameters, it will usually generate a closure. Why? Because the Python decorator is a fixed function interface form. It requires that your decorator function (or decorator class) must accept a function and return a function:
# how to define
Def wrapper (func1): # accept a callable object
Returnfunc2 # returns an object, usually a function
# how to use
Def target_func (args): # objective function
Pass
# call method 1, direct parcel
Result = wrapper (target_func) (args)
# call method 2, use @ syntax, which is equivalent to mode 1
@ wrapper
Def target_func (args):
Pass
Result = target_func ()
What if your decorator has parameters? Then you need to wrap another layer on the original decorator to receive these parameters. After these parameters (contraband) are passed to the inner decorator, the closure is formed. So when your decorator needs custom parameters, it usually forms a closure. (class decorator exception)
Defhtml_tags (tag_name):
Defwrapper_ (func):
Defwrapper (* args, * * kwargs):
Content = func (* args, * * kwargs)
Return "{content}" .format (tag=tag_name,content=content)
Returnwrapper
Returnwrapper_
@ html_tags (b)
Defhello (name= Toby):
Return Hello {}! .format (name)
# No @ is written as follows
# hello = html_tag (b) (hello)
# html_tag (b) is a closure that takes a function and returns a function
Printhello () # Hello Toby!
Printhello (world) # Hello world!
Let's take a look at what the package of a closure looks like. In fact, the closure function has a _ _ closure__ attribute relative to the ordinary function, which defines a tuple to store all the cell objects, and each cell object stores all the external variables in the closure one by one.
> > defmake_printer (msg1,msg2):
Defprinter ():
Printmsg1,msg2
Returnprinter
> printer = make_printer (Foo, Bar) # forms a closure
> printer.__closure__ # returns the cell tuple
()
> printer.__closure__ [0] .cell _ contents # first external variable
Foo
> printer.__closure__ [1] .cell _ contents # second external variable
Bar
Thank you for reading, the above is the content of "the concept and example analysis of closures in Python". After the study of this article, I believe you have a deeper understanding of the concept and example analysis of closures in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.