python:有没有一种方法可以在with statement中获取代码

2024-09-29 12:29:39 发布

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

我希望这能奏效:

class A:
    def __enter__(self, code):
       print code

    def __exit__(..):
       pass

然后:

^{pr2}$

将打印:

f()
g()

具体地说,我的目的是获取这些代码并从中创建一个函数。所以我可以做:with runInThreads()with runManyTimesTillSuccess(),。。在


Tags: 函数代码self目的defwithexitcode
3条回答

下面是如何使用带参数的修饰符:

>>> def manytimes(n):
    def decorate(fn):
        for i in range(n):
            fn()
    return decorate

>>> @manytimes(3)
def _():
    print("hello")


hello
hello
hello

但是,withhacks模块提供了几个特定于CPython的黑客行为的例子,让你做各种创造性的事情。在

不过,Python的官方代码块和生成器仍在使用。在

你为什么不找个装修工?在

我刚试过(我这里还有Python2.6.4,但它肯定也能用在较新的版本上)

def decorate(fn):
    print "Got", fn
    return "Anything"

def foo():
    @decorate
    def bar(): pass
    print bar

foo()
foo()

它给出了:

^{pr2}$

因此,您可以轻松做到:

any code...
@runInThreads
def _():
    whatever...

您甚至可以在函数中定义_任意次数。在

附言:我从withhacks读了link,然后想到了这一点,并想在那里发表评论,只是注意到comments there中已经提出了相同的技术。在

相关问题 更多 >