簡體   English   中英

包裝函數Python

[英]Wrapper Function Python

def suppress(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            pass
    return wrapper
def myfunc():
    print("foo")
    print("foo")

我在一本書中找到了這個代碼,並按照它的說法運行它......

suppress(myfunc)

這本書說應該運行這個功能但是會抑制它中的錯誤,這是在print("foo")而是,它只是給了我......

<function myfunc at 0x6981e0>

為什么???

您的suppress函數被設計為裝飾器,因此您需要將其應用於您的函數/方法。 慣用的方法是使用@語法,就像使用functools.wraps

import functools

def suppress(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            pass
    return wrapper

@suppress  # <-------- this is the idiomatic fix
def myfunc():
    "documentation"
    print("foo")
    raise ValueError

def myfunc2():
    "documentation"
    print("foo")
    raise ValueError

myfunc()  # prints "foo", does not raise exception
print myfunc.__doc__  # prints "documentation"

suppress(myfunc2)()  # functional style; prints "foo", does not raise exception
print suppress(myfunc2).__doc__  # prints "documentation"

上面的代碼示例中似乎有一個拼寫錯誤。 該代碼將無法運行,因為Python無法解析它(第11行的SyntaxError)。 如果你糾正了,也許我們可以看到真正的錯誤。

關於裝飾器的使用,要看到這種suppress ,你應該這樣做:

@suppress
def myfunc():
    ...
# errors suppressed in this call
myfunc()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM