首页 > 解决方案 > 覆盖在另一个函数中进行的函数调用的参数

问题描述

说,我有两个函数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"(但如果我可以输出两条消息,这是可以接受的)

标签: pythonpython-3.x

解决方案


如果传入的消息与要替换的消息匹配,您可以使用自定义函数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()

推荐阅读