有没有办法在python函数中的每个return语句之前执行一个语句?

时间:2021-10-20 03:59:46

For example i have this piece of code:

例如,我有这段代码:

def example():
    a = 'goodbye'
    if True:
        print a
        return 1
    else:
        print a
        return 0

I would like to know if there is any possible solution to write once "print a" and execute it before each "return" statement automaticaly. So that if I add more return statements I wouldn't need to add anything, but "print a" would execute. Result would look like something:

我想知道是否有任何可能的解决方案来编写一次“print a”并在每个“return”语句自动执行之前执行它。因此,如果我添加更多返回语句,我将不需要添加任何内容,但“print a”将执行。结果看起来像是:

def example():
    a = "goodbye"
    """ some code to implement print a """
    if True:
        return 1
    else:
        return 0

Each time there is return statement it still would print a.

每次有return语句时它仍会打印一个。

I tried to google, but don't know how word query, since all results are about returning multiple values.

我试图谷歌,但不知道单词查询,因为所有结果都是关于返回多个值。

UPDATE: My question was answered, thanks to all of you.
Although wrapping functions are correct answer, but I have chosen answer by GingerPlusPlus who suggested to use try...finally for simplicity.

更新:感谢你们所有人,我的问题得到了回答。虽然包装功能是正确的答案,但我选择了GingerPlusPlus的答案,他建议使用try ...最后为了简单。

6 个解决方案

#1


4  

try .. finally:

试试..终于:

def example():
    try:
       if True:
           return 1
       else:
           return 0
    finally:
        print 'goodbye'

>>> example()
goodbye
1

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Docs

在离开try语句之前总是执行finally子句,无论是否发生了异常。文件

#2


8  

You can use a context. Initialize it with the value you want to print. Then print when context exit, i.e. upon return.

您可以使用上下文。使用要打印的值对其进行初始化。然后在上下文退出时打印,即在返回时打印。

class PrinterOnContextExit():
    def __init__( self, a ): self.a = a
    def __enter__( self ): pass
    def __exit__( self, exc_type, exc_value, traceback ): print( self.a )

def example():
    a = 'goodbye'
    with PrinterOnContextExit( a ):
        if True:
            return 1
        else:
            return 0

Note that you cannot print the returned value this way. If you ever wanted to print the returned value, then you should use a decorator.

请注意,您无法以这种方式打印返回的值。如果您想打印返回的值,那么您应该使用装饰器。

class PrintOnReturn():
    def __init__( self, a ): self.a = a
    def __call__( self, func ): return lambda *args, **kwargs: self.callFunc( func, *args, **kwargs )
    def callFunc( self, func, *args, **kwargs ): r = func( *args, **kwargs ); print( self.a, r ); return r

@PrintOnReturn( "hello" )
def example():
    if True:
        return 1
    else:
        return 0

This will print whatever string you passed to the decorator, followed by the value returned from the decorated function. Here hello 1.

这将打印您传递给装饰器的任何字符串,然后是装饰函数返回的值。你好1。

#3


3  

Code:

def example():
    a = 'goodbye'
    print a
    if True:
        return 1
    else:
        return 0

If you print a before if else then it will print value every time you call the function.

如果您打印之前的if if,那么每次调用该函数时它都会打印值。

#4


2  

You could also use a decorator, if it suits your case:

你也可以使用装饰器,如果它适合你的情况:

>>> def decorator(text):
...     def wrapped(func):
...         def inner(*args, **kwargs):
...             result = func(*args, **kwargs)
...             print text
...             return result
...         return inner
...     return wrapped
... 

>>> @decorator('goodbye')
... def example():
...     return True
... 

>>> example()
goodbye
>>> True

Decorator will allow you to print any text after the decorated function was called. Or before.

装饰器将允许您在调用修饰函数后打印任何文本。或之前。

#5


2  

Create a value returnval

创建值returnval

returnval = 0  #default value
testval = 0 # Code to set up if
# code to set various values of testval
if testval == 0:
    returnval = 1
elif testval == 5:
    returnval = 2
else:
    returnval = 10

print a
return returnval

#6


1  

Def example():
a = 'goodbye'
if True:
return 1,str(a)
    else:
     return 0,str(a)
print example()

Thats the only way...I dont think there is a way to avoid typing what you want to be printed...sorry mate! expect if you type a function type the thinks you

这是唯一的方法......我不认为有办法避免键入你想要打印的东西......对不起伙计!期待你输入一个认为你的函数类型

#1


4  

try .. finally:

试试..终于:

def example():
    try:
       if True:
           return 1
       else:
           return 0
    finally:
        print 'goodbye'

>>> example()
goodbye
1

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Docs

在离开try语句之前总是执行finally子句,无论是否发生了异常。文件

#2


8  

You can use a context. Initialize it with the value you want to print. Then print when context exit, i.e. upon return.

您可以使用上下文。使用要打印的值对其进行初始化。然后在上下文退出时打印,即在返回时打印。

class PrinterOnContextExit():
    def __init__( self, a ): self.a = a
    def __enter__( self ): pass
    def __exit__( self, exc_type, exc_value, traceback ): print( self.a )

def example():
    a = 'goodbye'
    with PrinterOnContextExit( a ):
        if True:
            return 1
        else:
            return 0

Note that you cannot print the returned value this way. If you ever wanted to print the returned value, then you should use a decorator.

请注意,您无法以这种方式打印返回的值。如果您想打印返回的值,那么您应该使用装饰器。

class PrintOnReturn():
    def __init__( self, a ): self.a = a
    def __call__( self, func ): return lambda *args, **kwargs: self.callFunc( func, *args, **kwargs )
    def callFunc( self, func, *args, **kwargs ): r = func( *args, **kwargs ); print( self.a, r ); return r

@PrintOnReturn( "hello" )
def example():
    if True:
        return 1
    else:
        return 0

This will print whatever string you passed to the decorator, followed by the value returned from the decorated function. Here hello 1.

这将打印您传递给装饰器的任何字符串,然后是装饰函数返回的值。你好1。

#3


3  

Code:

def example():
    a = 'goodbye'
    print a
    if True:
        return 1
    else:
        return 0

If you print a before if else then it will print value every time you call the function.

如果您打印之前的if if,那么每次调用该函数时它都会打印值。

#4


2  

You could also use a decorator, if it suits your case:

你也可以使用装饰器,如果它适合你的情况:

>>> def decorator(text):
...     def wrapped(func):
...         def inner(*args, **kwargs):
...             result = func(*args, **kwargs)
...             print text
...             return result
...         return inner
...     return wrapped
... 

>>> @decorator('goodbye')
... def example():
...     return True
... 

>>> example()
goodbye
>>> True

Decorator will allow you to print any text after the decorated function was called. Or before.

装饰器将允许您在调用修饰函数后打印任何文本。或之前。

#5


2  

Create a value returnval

创建值returnval

returnval = 0  #default value
testval = 0 # Code to set up if
# code to set various values of testval
if testval == 0:
    returnval = 1
elif testval == 5:
    returnval = 2
else:
    returnval = 10

print a
return returnval

#6


1  

Def example():
a = 'goodbye'
if True:
return 1,str(a)
    else:
     return 0,str(a)
print example()

Thats the only way...I dont think there is a way to avoid typing what you want to be printed...sorry mate! expect if you type a function type the thinks you

这是唯一的方法......我不认为有办法避免键入你想要打印的东西......对不起伙计!期待你输入一个认为你的函数类型