In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand the closure Closure in Python? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Closures in Python are not an easy concept to understand, but as you learn more, you need to understand such a thing anyway.
The concept of closure
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.
Wikipedia)
In easier-to-understand words, when a function is returned as an object, with an external variable, a closure is formed. Look at the example.
Def make_printer (msg): def printer (): print msg # with contraband (external variable) return printer # returns a function, and the function with contraband printer = make_printer ('foodies') Printer ()
A programming language that supports functions as objects, and generally supports closures. Such as Python, JavaScript.
How to understand closures
What's the point of closures? Why do you need closures?
I personally think that 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.
Interface defines a set of constraint rules for method signatures.
Def tag (tag_name): def add_tag (content): return "{1}" .format (tag_name, content) return add_tag content = 'Hello' add_tag = tag (' a') print add_tag (content) # Hello add_tag = tag ('b') print add_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 an callable object return func2 # return an object, usually function # how to use def target_func (args): # target function pass # call method 1, directly wrap result = wrapper (target_func) (args) # call mode 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)
Def html_tags (tag_name): def wrapper_ (func): def wrapper (* args, * * kwargs): content = func (* args, * * kwargs) return "{content}" .format (tag=tag_name Content=content) return wrapper return wrapper_ @ html_tags ('b') def hello (name='Toby'): return 'Hello {}!' .format (name) # hello = html_tag ('b') (hello) # html_tag ('b') is a closure It takes a function and returns a function print hello () # Hello Toby! Print hello ('world') # Hello world!
For a more in-depth analysis of the decorator, you can see another blog I wrote.
A little deeper.
In fact, you don't have to go too deep to understand the concepts above, and that's all for a lot of code that looks like a headache.
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.
> def make_printer (msg1, msg2): def printer (): print msg1, msg2 return printer > printer = make_printer ('Foo',' Bar') # form closure > printer.__closure__ # returns cell tuple ( ) > printer.__closure__ [0] .cell _ contents # * external variable 'Foo' > printer.__closure__ [1]. Cell _ contents # second external variable' Bar'
The principle is that simple.
This is the answer to the question about how to understand the closure Closure in Python. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.