python - 覆盖在另一个函数中进行的函数调用的参数
问题描述
说,我有两个函数bar()
和foo()
. bar()
执行foo()
。
def foo():
try:
num = int( input("need an Integer") )
except ValueError:
print("input invalid")
def bar():
foo()
当我运行bar()
并输入一个非整数值时,我应该获得"input invalid"
消息。但是,如果我想"input invalid"
在bar()
不修改foo()
. 我应该怎么办?
我尝试了以下方法,但这不起作用。
def foo():
try:
num = int( input("need an Integer") )
except ValueError:
print("input invalid")
def bar():
try:
foo()
except Exception as result: <-- this does not capture the error in foo()
print("my customized error message")
期望的输出是:"my customized error message"
而不是"input invalid"
(但如果我可以输出两条消息,这是可以接受的)
解决方案
如果传入的消息与要替换的消息匹配,您可以使用自定义函数unittest.mock.patch
临时覆盖内置print
函数,该函数使用原始函数打印所需的消息,或者按原样打印消息:print
from unittest.mock import patch
def custom_print(s, *args, **kwargs):
orig_print("my customized error message" if s == "input invalid" else s, *args, **kwargs)
orig_print = print
def bar():
with patch('builtins.print', new=custom_print):
foo()
bar()
推荐阅读
- sql - 如何计算表中某列中具有相同值的行数?
- javascript - 如何将第二个底部标题添加到 Tabulator.js?
- javascript - 反应原生渲染按钮列表无法找出问题所在
- shedlock - ShedLock - 不执行
- javascript - 如何在 Javascript 中获取包含子字符串的完整字符串?
- typescript - 打字稿错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型
- javascript - Tensorflow JS 损失没有改变
- python - 如何从 CSV 生成深度嵌套的 JSON?
- c# - HDF5 C# pinvoke 读取数据集名称列表
- xaml - 将 OnIdiom 与 AbsoluteLayout 一起使用