将参数传递给__

2024-10-06 12:24:39 发布

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

只是学习语句especially from this article

问题是,我能给__enter__传递一个参数吗?

我有这样的代码:

class clippy_runner:
    def __enter__(self):
        self.engine = ExcelConnection(filename = "clippytest\Test.xlsx")
        self.db = SQLConnection(param_dict = DATASOURCES[STAGE_RELATIONAL])

        self.engine.connect()
        self.db.connect()

        return self

我想将文件名和参数dict作为参数传递给__enter__。有可能吗?


Tags: 代码fromselfdb参数connectarticle语句
3条回答

您可以使用contextmanager装饰器传递参数:

https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager

from contextlib import contextmanager

@contextmanager
def clippy_runner(*args):
    yield

我发现,使用contextmanager可以提供参数,但不能将它们提供给__enter__这让我感到困惑

是的,您可以通过添加一点代码来获得效果。


    #!/usr/bin/env python

    class Clippy_Runner( dict ):
        def __init__( self ):
            pass
        def __call__( self, **kwargs ):
            self.update( kwargs )
            return self
        def __enter__( self ):
            return self
        def __exit__( self, exc_type, exc_val, exc_tb ):
            self.clear()

    clippy_runner = Clippy_Runner()

    print clippy_runner.get('verbose')     # Outputs None
    with clippy_runner(verbose=True):
        print clippy_runner.get('verbose') # Outputs True
    print clippy_runner.get('verbose')     # Outputs None

不。你不能。你把参数传递给__init__()

class ClippyRunner:
    def __init__(self, *args):
       self._args = args

    def __enter__(self):
       # Do something with args
       print(self._args)


with ClippyRunner(args) as something:
    # work with "something"
    pass

相关问题 更多 >