簡體   English   中英

在 python 中,有沒有辦法讓函數/類表現得像一個函數和一個上下文管理器?

[英]In python is there a way to make a function/class that behaves like a function and a context manager?

在 python 中,有沒有辦法讓函數/類表現得像一個函數和一個上下文管理器?

注意:我需要函數/類來返回一個沒有__exit__方法的對象,並且我無法更改該對象(這就是我包裝它的原因)。

所以僅僅用__enter____exit__制作一個類是__enter__ ,因為我需要它也表現得像一個函數。

我試過contextmanager裝飾器:

@contextmanager
def my_context_man(my_str):
    my_str = 'begging ' + my_str
    yield my_str+' after func'
    print('end')

它在上下文管理器中完美運行,但不是作為一個函數:

a = 'middle'
old_a = my_context_man(a)
print('old_a', old_a)

with my_context_man(a) as new_a:
    print('new_a', new_a)

輸出:

old_a <contextlib._GeneratorContextManager object at 0x0000000004F832E8>
new_a begging middle after func
end

而所需的輸出將是:

old_a begging middle after func
new_a begging middle after func
end

編輯:我遇到的具體問題是psycopg2模塊。 我想使用不同的上下文管理器。 它返回一個連接對象。

def connect(dsn=None, connection_factory=None, cursor_factory=None, **kwargs):
    *the connection code*    
    return conn

我正在嘗試更改它,以便人們能夠將它與我的上下文管理器一起使用,但不會破壞代碼。 無法更改 conn 對象

您的__new__方法不返回my_context_man的實例,而是返回str的實例,並且str沒有__enter__方法。 它的返回值__enter__是被綁定到名字后, aswith聲明。 你要

class my_context_man:
    def __init__(self, my_str):
        self.msg = my_str
        print("beginning " + my_str)

    def __enter__(self):
        return self.msg

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('end') 

暫無
暫無

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

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