📜  Python中收益和回报之间的区别

📅  最后修改于: 2022-05-13 01:54:45.282000             🧑  作者: Mango

Python中收益和回报之间的区别

Python产量
它通常用于将常规Python函数转换为生成器。生成器是Python中的一个特殊函数,它将生成器对象返回给调用者。由于它存储局部变量状态,因此控制了内存分配的开销。

例子:

# Python3 code to demonstrate yield keyword 
  
# Use of yield
def printresult(String) : 
    for i in String: 
        if i == "e": 
            yield i 
  
# initializing string 
String = "GeeksforGeeks" 
ans = 0
print ("The number of 'e' in word is : ", end = "" ) 
String = String.strip() 
  
for j in printresult(String): 
    ans = ans + 1
  
print (ans) 

输出:

The number of 'e' in word is : 4

Python返回
它通常用于执行结束并将结果“返回”给调用者语句。它可以返回所有类型的值,当没有带有“return”语句的表达式时,它返回 None。

例子:

# A Python program to show return statement 
class Test:  
    def __init__(self):  
        self.str = "GeeksForGeeks"
        self.x = "Shubham Singh"   
      
# This function returns an object of Test  
def fun():  
    return Test()  
          
# Driver code to test above method  
t = fun()   
print(t.str)  
print(t.x) 

输出:

GeeksForGeeks
Shubham Singh

Python yield 和 Return 之间的区别

S.NO.YIELDRETURN
1Yield is generally used to convert a regular Python function into a generator.Return is generally used for the end of the execution and “returns” the result to the caller statement.
2It replace the return of a function to suspend its execution without destroying local variables.It exits from a function and handing back a value to its caller.
3It is used when the generator returns an intermediate result to the caller.It is used when a function is ready to send a value.
4Code written after yield statement execute in next function call.while, code written after return statement wont execute.
5It can run multiple times.It only runs single time.
6Yield statement function is executed from the last state from where the function get paused.Every function calls run the function from the start.