In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "Python full stack scope and how to use closures". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1.return return value # return custom function return value "" concept: return returns the data inside the function to the outside of the function, to the function call place 1.return + six standard data types, in addition, you can also return the function or class object 2.return when executing, which means that the function is terminated, and the following code does not execute .3. If the return return value is not defined, None "" # (1) return + six standard data types def func () is returned by default: # return 111 # return 6.89 # return "you are so handsome, I love you so much" # return [1jue 2jue 3] # return {"a": 1, "b": 2} return 1prit 2 3 # return tuple res = func () print (res) # (2) return when executed, it means terminating the function The following code does not execute .def func (): print (1) print (2) return 3 print (4) res = func () print (res) def func (): for i in range (5): if I = = 3: return 4 print (I) res = func () print (res) # (3) if return is not defined Nonedef func () is returned by default: passres = func () print (res) # None# Note that the printed data and the returned data are not equivalent, and the returned data can be customized Res = print (1234) print (res) # None# Analog +-* / Calculator "" function: complete calculation parameters: 2 numbers and operator return value: calculated result "def calc (num1,num2) Sign): if sign = "+": return num1 + num2 elif sign = = "-": return num1-num2 elif sign = = "*": return num1 * num2 elif sign = = "/": if num2 = = 0: return "Divisor cannot be zero" Return num1 / num2 else: return Sorry It is beyond the scope of my operation. "res = calc (3jue 5," + ") res = calc (3jue 5,"-") res = calc (3jue 5," * ") res = calc (3jue 0," / ") res = calc (3jue 0," & ") print (res) 2. Global variable _ local variable # Global variable and local variable "" 1. Concept local variables: variables defined inside the function are local variables global variables: variables defined outside the function or declared to be global variables using the global keyword inside the function 2. Scope: the scope of local variables is only within the internal scope of the function, and the scope of global variables spans the entire file 3. Life cycle: the duration of this variable is built-in namespace-> global namespace-> local namespace (open space order) built-in attribute > global attribute > local attribute (duration: long-> short) "# 1 local variable def func (): # define a local variable a = 1 # Get the current local variable print (a) # modify a local variable a = 2 print (a) func () # print (a) error# 2. Global variable # defines a global variable b = 1 global gets the current global variable print (b) # modifies a global variable b = 20print (b) def func (): print (b) func () # 3. The function defines a global variable def func (): global c c = 30func () print (c) # 4. Modify the global variable within the function d = 50def func (): global d d = 51func () print (d) "" Summary: the use of global if there is no global variable currently, you can define the global variable inside the function through the global keyword. If the global variable currently exists, you can modify the global variable "" through the global keyword inside the function. "
3. The function name can be dynamically created and destroyed like a variable. When the parameter is passed and returned as a value, it is called the first class object. Other languages have limited functionality "def func (): print (" I am the func function ") # (1) dynamically create a = 1print (a) a = funca () # (2) dynamically destroy del a # a () # func () # (3) when the parameter passes def func2 (): return" I am the func2 function "def func1 (f): return f () #" I am the func2 function "res = func1 (func2) print (res) # (4) returns def func3 () as a value: print (" I am a func3 function ") def func4 (f): return fres = func4 (func3) print (res) res () print (") # (5) the function name can be used as an element of container type data lst = [func " Func3] for i in lst: I () print (") # _ doc__ or help View document def big_chang_cishen (something):" function: teach you how to eat large intestine parameters: what you eat: return value: whether you are satisfied "" print "(" wash {} ".format (something) ) print ("find the head of the intestine directly Put it in your mouth and inhale ") print (" wipe your mouth and put down your intestines satisfactorily ") return" finished, it's delicious ~ "big_chang_cishen (" raw intestines ") # method 1 res = big_chang_cishen.__doc__print (res) # method 2 help (big_chang_cishen) 4. The nesting of functions 4.1 the nesting of functions # the nesting of functions "" two functions nesting each other! [please add picture description] (the outer function wrapped by https://img-blog.csdnimg.cn/f3ab3fd8502e43eebd473306c0e28633.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA54as5aSc5rOh6p645p2e,size_20,color_FFFFFF,t_70,g_se,x_16): is called outer function. The inner layer is the inner function "" def outer (): # inner () def inner (): print ("I am the inner function") "# (1) can the internal function be called directly outside the function? no # inner () # (2) after calling the external function Can the internal function be called outside the function? no # outer () # inner () # (3) can the internal function be called inside the function? can you outer () # (4) when the internal function is called within the function, whether there is a sequence of some # defined in the call # there is a preloading mechanism in other languages to reside the function in memory in advance. Then compile the content of the script # python has no mechanism to preload the function, so it can only be defined before calling the # the outer function is outer, the intermediate function is inner, and the innermost layer is smaller Call the smaller function def outer (): def inner (): def smaller (): print ("I am a smaller function") smaller () inner () outer () # LEGB principle def outer (): def inner (): def smaller (): Print (a) smaller () inner () outer () "" LEGB principle (nearest variable finding principle) # the calling order of finding variables is based on LEGB principle (that is, nearest principle) B-Builtin (Python) The namespace of the Python built-in module (built-in scope) G-- Global (module); the namespace outside the function (global scope) E-- the scope of the Enclosing function locals; external nested function (nested scope) L-- Local (function); the scope within the current function (local scope) looks for "" from bottom to top and from inside to outside according to the proximity principle
4.2 use of nonlocal # use of nonlocal (used to modify local variables) "" nonlocal follows the LEGB principle (1) it will find variables above the current space to modify (2) if the space above is not available, continue to look up (3) if you can't find it in the end. Directly report an error "" # (1) it will find the variable above the current space to modify def outer (): a = 10 def inner (): nonlocal an a = 20 print (a) inner () print (a) outer () # (2) if the upper space is not available Continue to find def outer (): a = 20 def inner (): a = 15 def smaller (): nonlocal an a = 30 print (a) smaller () print (a) inner () print (a) outer () # (3) if not found in the end Direct error "" nonlocal can only modify local variables. "a = 20def outer (): def inner (): def smaller (): nonlocal an a = 30 print (a) smaller () print (a) inner () print (a) outer () error "" # (4) is it possible to modify local variables without nonlocal? okdef outer (): lst = [1jue 2 3] def inner (): lst [- 1] = 3000 inner () print (lst) outer () 5. The definition of the closure function is the process in which the inner function uses the local variable of the outer function and the outer function returns the inner function, if the inner function uses the local variable of the outer function and the outer function returns the inner function, is it a closure? 1. The inner function uses the local variable of the outer function. 2. The outer function returns the inner function "# 1". Basic grammatical form def zhaoshenyang_family (): father = "Jack Ma" def hobby (): print ("I don't have the slightest interest in money. I don't value money." This is what my father {} said: .format (father) return hobbyfunc = zhaoshenyang_family () func () print ("") tup = func.__closure__print (tup [0] .cell _ contents) # Jack Ma print (tup) print (") # 2. The complex form of closure def zhaowanli_family (): gege = "Wang Sicong" didi = "Shoe King, Gao Zhenning" money = 1000 def gege_hobby (): nonlocal money money-= 500 print ("I don't care whether he has money or not, he doesn't have as much money as I do." I like to have girlfriends. Money and goods left {} ".format (money) def didi_hobby (): nonlocal money money-= 400print (" there are shoe cabinets at home, all kinds of luxury shoes, a pair of about 20-300000, money and goods left {} ".format (money)) def big_master (): return [gege_hobby Didi_hobby] return big_masterfunc = zhaowanli_family () print (func) lst = func () print (lst) # get brother function gege = lst [0] gege () # get brother function didi = lst [1] didi () # 3. Using _ _ closure__, cell_contents determines the closure "" if there is data in the returned tuple indicating that it is a closure, print whose life cycle is extended "tup = func.__closure__print (tup) # first get the contents of the first cell cell_contents in the object func1 = tup [0] .cell _ contentsprint (")" print closure function didi_hobby Life cycle extended attribute "" print (func1.__closure__ [0] .cell _ contents) func1 () # in getting the contents of the second cell cell_contents acquisition object func2 = tup [1] .cell _ contentsprint (")" in the print closure function gege_hobby, the life cycle extended attribute "" print (func2.__closure__ [0] .cell _ contents) func2 ()
6. Characteristics of closures # the characteristics of closures: in the closure function, the inner function uses the local variable of the outer function, which will be bound to the inner function to prolong the life cycle of the variable. Continues until the end of script execution. "" def outer (val): def inner (num): return val + num return innerfunc = outer (10) res = func (15) print (res) # the meaning of the closure "the scope of the global variable is large It is easy to tamper with "" num = 0def click_num (): global num num + = 1 # num = num + 1 print (num) click_num () num = 100click_num () click_num () # transformation, using closures to realize the meaning of closures: closures can give priority to variables in external functions, and play a role in encapsulating and protecting the values in closures. Cannot be accessed externally. "" def outer (): X = 0 def click_num (): nonlocal x x + = 1 print (x) return click_numclick_num = outer () click_num () x = 100click_num () click_num () Tip: def outer (): a = 10 Def inner (): a = 20 print (a) inner () print (a) outer () the output here is 20 10 The non-interference list of two a variables in the nest can directly pass values in the internal and external functions. When modifying the list, you do not need to use nolocal to modify the values of the variables. Closures can prolong the period of local variables. There is no way to modify a global variable inside the function. It must pass a global (same as nonlocal) 7. Small exercise # # 1. Define the function: accept any parameter and print the minimum value def func (* args): lst = [] for i in args: if isinstance (I, (float,int)): lst.append (I) print (lst) return lst [0] res = func (- 100meme 1m 423, "sdf") print (res) # 2. Define the function: pass in a parameter n and return the factorial of n (5! = 5 "4" 3 "2" 1) def func (n): total = 1 for i in range (nmemo Lindi 1): total * = i return totalprint (func (5)) # 3. Write function, pass in multiple arguments in the function (all are iterable objects such as string, list, meta-ancestor, collection, etc.) # # add each element in the container to the new list in turn and return # examples: two arguments to the incoming function, [1 ~ 2 ~ 2 ~ 3] (22 ~ 2 ~ 33), the final args is (1 ~ 2 ~ 2) 3 args 22) # method 1 def func (* args): lst = [] for i in args: for j in i: lst.append (j) return lstres = func ([1 minus 2 maire3], (5 maestro 6 piont 7), "abc") print (res) # method 2 def func (* args): return list (args) res = func (* [1 meme 2 mori3], * (5 pyrrine 6 p7) * "abc") print (res) # 4. Write the function, the user passes in the name of the file to be modified, and execute the function with the content to be modified Modify operation # method # def func (filename,str1,str2): with open (filename,mode= "r +", encoding= "utf-8") as fp: strvar = fp.read () print (strvar) res = strvar.replace (str1,str2) with open (filename,mode= "w +") Encoding= "utf-8") as fp: fp.write (res) func ("ceshi2.py", "built-in function", "external function") # method II def func (filename,str1,str2): with open (filename,mode= "r +", encoding= "utf-8") as fp: strvar = fp.read () res = strvar.replace (str1 Str2) # print (fp.tell ()) fp.seek (0) # clear fp.truncate () fp.write (res) func ("ceshi2.py", "external function", "built-in function") # 5. Write function Calculate the number of [numbers], [letters], [spaces] and [other] in the passed string # method-def func (strvar): dic = {"num": 0, "word": 0, "space": 0 "other": 0} for i in strvar: if i.isdecimal (): dic ["num"] + = 1 # dic ["num"] = dic ["num"] + 1 elif i.encode (). Isalpha (): dic ["word"] + = 1 elif i.isspace (): Dic ["space"] + = 1 else: dic ["other"] + = 1 return dic# strvar = input ("Please enter a string") # print (func (strvar)) "print (" you ".isalpha ()) # Chinese = > Falseprint (" you ".encode ()) # letter = > Trueprint (" a ".encode () .isalpha () "" # method II def func (strvar): dic = {"num": 0 "word": 0, "space": 0 "other": 0} lst = [] for i in range (97123): lst.append (chr (I)) lst.append (chr (Imur32)) for i in strvar: if i in "0123456789": dic ["num"] + = 1 elif i in lst: Dic ["word"] + = 1 elif I = = "": dic ["space"] + = 1 else: dic ["other"] + + = 1 return dic# strvar = input ("Please enter string") # print (func (strvar)) # 6. Write a function to check the length of each value in the dictionary. If it is greater than 2, only the contents of the first two lengths are retained and the processed results are returned. # example: parameter is: dic = {"K1": "v1v1", "K2": [11 def func 22 3Mae 44]} def func (dic): if isinstance (dic,dict): for K1 v in dic.items (): print (k V) dic [k] = v [: 2] return dic else: return "is not a dictionary" dic = {"K1": "v1v1", "K2": [11pime 22pyrt 3je 44]} print (func (dic)) print (func ([1pr 23mrt 44je 235e 4234]) # 7 input multiple container type data Calculate the number of elements def func (* args): total = 0 for i in args: print (I) total + = len (I) return totalres = func Do not judge the length of the string itself def func (* args): total = 0 for i in args: print (I) if isinstance (iMagnestr): total + = 1 elif isinstance (I, (tuple,list,set,dict)): total + = len (I) return totalres = func ("Hello", "123423")) print (res) "Python full stack scope and how to use closures" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.