考虑这个 Python 片段:
def someTestFunction():
if someTest:
return value1
elif someOtherTest:
return value2
elif yetSomeOtherTest:
return value3
return None
def SomeCallingFunction():
a = someTestFunction()
if a != None:
return a
... normal execution continues
现在,问题是:SomeCallingFunction 开头的三行代码段用于获取测试函数的值,如果它不是 None 则退出,在许多其他函数中经常重复。三行太长了。我想把它缩短为一个。我该怎么做?
我可以根据需要自由重构此代码和 someTestFunction 的内容。我考虑过使用异常,但这些似乎对减少调用代码长度没有帮助。
(我已经阅读了一些关于 Python 装饰器的内容,但还没有使用过它们。会是这个地方吗?它是如何工作的?)
最佳答案
如果你想使用装饰器,它看起来像这样:
def testDecorator(f):
def _testDecorator():
a = someTestFunction()
if a is None:
return f()
else: return a
return _testDecorator
@testDecorator
def SomeCallingFunction():
... normal execution
首次导入模块时,它会运行 testDecorator
,将您的原始 SomeCallingFunction
作为参数传递给它。返回一个新函数,并绑定(bind)到 SomeCallingFunction
名称。现在,无论何时调用 SomeCallingFunction
,它都会运行另一个函数,它会进行检查,并返回 a
或原始 SomeCallingFunction
的结果>.
关于python - 缩短用于测试 Python 返回值的常用代码段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/694775/