In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use the Python generator". Many people will encounter such a 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!
Generator
Just have the ability to generate something, and it's not worth it if you don't use the _ _ next__ method.
Create a generator function
> def scq (): Print ("11") # when the yield keyword is encountered in the function code block, this function is a generator function. Yield 1... Print ("22"). Yield 2... Print ("33"). Yield 3...
Assign a generator to an object
> r = scq ()
Check the Su opera type of r and output the value of r
> print (type (r), r)
When the _ _ next__ of the generator is executed, the code will be executed in order, and when it reaches yield, it will return and propose that the value after yield is the return value, and then record the location of the code execution and exit.
Execution result
C:Python35python.exe F:/Python_code/sublime/Week5/Day03/s1.py0 1 2 3 4Process finished with exit code 0 iterator
Have the ability to access the generator, can access the value of the generator, similar to the generator's _ _ next__ method, a value is worth iterating, can only be found sequentially.
Features:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Visitors don't need to care about the internal structure of the iterator, just keep fetching the next content through the next () method.
You cannot randomly access a value in the collection, only from beginning to end
You can't go back in the middle of the visit.
It is easy to cycle large data sets and save memory.
Optimize the generator for range or xrange above
Def irange (start, stop, step=1): while start! = stop: yield start start + = step else: raise StopIteration for n in irange (1,10): "" for loop will stop whenever it encounters StopIteration "" print (n) ret = irange (1,20) print (ret) # returns a generator, which is equivalent to creating only one value print (list (ret)) # if you want to get all the values Become a list of decorators for / Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 / Users/ansheng/MyPythonCode/hello.py 12 3 4 5 6 7 8 9 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Process finished with exit code 0Python
Now to perform some actions before and after executing the func function, you can create a decorator to implement:
#! / usr/bin/env python # _ * _ coding: utf-8 _ * _ def decorator (func): # create a decorator function. The parameter arg is the func function name def inner (* args, * * kwargs): print (before executing the function) ret = func (* args, * * kwargs) print (after executing the function) return ret return inner @ decorator # if you want a function to use the decorator Just add the @ + decorator name def func (arg): print (arg) func ("Hello World!") to this function.
The output is as follows:
/ usr/bin/python3.5 / home/ansheng/Documents/PycharmProjects/blogcodes/ decorator. Py executes the function before Hello World! Process finished with exit code 0 after the function is executed
Multiple decorators decorate the same function
#! / usr/bin/env python # _ * _ coding: utf-8 _ * _ def decorator1 (func): def inner (): print ("execute decorator 01 before starting") ret = func () print ("execute decorator 01 after completion") return ret return inner def decorator2 (func): def inner (): print ("decorator2 > Start...") Ret = func () print ("decorator2 > End...") Return ret return inner @ decorator1 @ decorator2 def index (): print ("execute function...") Index ()
Output result:
/ usr/bin/python3.5 / home/ansheng/Documents/PycharmProjects/blogcodes/ decorator execute decorator 01 decorator2 > Start... before py starts Execute the function. Decorator2 > > End... Execute decorator 01 Process finished with exit code 0 after finishing
More Instanc
#! / usr/bin/env python
# _ * _ coding:utf-8 _ * _
# Created by Anson on 2017-2-9
"
Function decorator
"
Def decorator (func):
Def wrapped (* args, * * kwargs):
Return func (* args, * * kwargs)
Return wrapped
@ decorator
Def func (a, b):
Return a + b
Print (func (1,2))
"
Class decorator
"
Class decorator:
Def _ _ init__ (self, func):
Self.func = func
Def _ _ call__ (self, * args, * * kwargs):
Return self.func (* args, * * kwargs)
@ decorator
Def func (a, b):
Return a + b
Print (func (1,2))
"
Function decorator with parameters
"
Def parameter (a, b):
Print (a, b)
Def decorator (func):
Def wrapped (* args, * * kwargs):
Return func (* args, * * kwargs)
Return wrapped
Return decorator
@ parameter (1,2)
Def func (a, b):
Return a + b
Print (func (10,20))
"
Class decorator with parameters
"
Def parameter (a, b):
Print (a + b)
Class decorator:
Def _ _ init__ (self, func):
Self.func = func
Def _ _ call__ (self, * args, * * kwargs):
Return self.func (* args, * * kwargs)
Return decorator
@ parameter (1,2)
Def func (a, b):
Return a + b
Print (func (10,20))
"
Class decorator with parameters
"
Def parameter (a, b):
Print (a, b)
Def decorator (cls):
Class wrapped:
Def _ _ init__ (self, * args, * * kwargs):
Self.cls = cls (* args, * * kwargs)
Def _ _ getattr__ (self, item):
Return getattr (self.cls, item)
Return wrapped
Return decorator
@ parameter (1,2)
Class CLS:
Def _ init__ (self):
Self.a ='a'
Def P (self, v):
Print (v)
Obj = CLS ()
Print (obj.a)
Obj.P ('Hello,')
"
Add decorators for methods in functions and classes
"
Def Call (aClass):
Calls = 0
Def onCall (* args, * * kwargs):
Nonlocal calls
Calls + = 1
Print ('call% s to% s'% (calls, func.__name__))
Return aClass (* args, * * kwargs)
Return onCall
@ Call
Def func (a, b):
Return a + b
Print (func (1,2))
Class CLS:
Def _ init__ (self):
Self.a ='a'
@ Call
Def b (self):
Return self.a
Obj = CLS ()
Print (obj.b ())
That's all for "how to use the Python Generator". Thank you for 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.