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

标签 python python-2.7

例如我有这段代码:

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

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

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

每次有返回语句它仍然会打印一个。

我尝试用 google 搜索,但不知道如何查询,因为所有结果都是关于返回多个值。

更新:感谢大家,我的问题得到了解答。
虽然包装函数是正确答案,但我选择了 GingerPlusPlus 的答案。为了简单起见,谁建议使用 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

关于python - 有没有办法在python函数的每个return语句之前执行一条语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336856/

相关文章:

python - 为什么 tensorflow 和 numpy 的特征值输出不同?

python - 查找列表中第一个正元素的索引 - python

python - 为什么列表元素替换比 python 中的字符串元素替换慢?

python - 动态生成方法,给出字典的键

python - 更改嵌套列表中的单个值时多个值会发生变化

python - 如何使用二进制文件读取和写入值

python - 错误: the tensor's graph is different from the session's graph

python - 类似于 scipy.interpolate.griddata?

python - MySQL 连接器不工作 : NO module named Connector

python - TensorFlow 中的矩阵逆