在python中,有没有一种方法可以使函数/类的行为类似于函数和上下文管理器?

2024-04-20 15:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,有没有一种方法可以使函数/类的行为类似于函数和上下文管理器?你知道吗

注意:我需要函数/类返回一个没有__exit__方法的对象,并且我不能更改该对象(这就是我包装它的原因)。你知道吗

所以仅仅用__enter____exit__创建一个类是行不通的,因为我需要它也像函数一样工作。你知道吗

我试过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对象


Tags: 对象函数middle管理器newmycontextold
1条回答
网友
1楼 · 发布于 2024-04-20 15:42:42

您的__new__方法没有返回my_context_man的实例,但是str的实例和str没有__enter__方法。是__enter__的返回值绑定到with语句中as后面的名称。你想要什么

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') 

相关问题 更多 >