47

特にこの記事からのステートメントについて学ぶだけです

問題は、に引数を渡すことはでき__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

filename と param_dict をパラメーターとして に渡したいと思います__enter__。それは可能ですか?

4

6 に答える 6

48

いいえ、できません。に引数を渡します__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
于 2011-02-24T19:41:03.033 に答える
46

はい、もう少しコードを追加することで効果を得ることができます。


    #!/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
于 2012-04-20T20:12:03.317 に答える
3

Wouldn't you just pass the values to __init__ via the class constructor?

于 2011-02-24T19:42:01.427 に答える