2024-09-29 12:29:39 发布
网友
我希望这能奏效:
class A: def __enter__(self, code): print code def __exit__(..): pass
然后:
将打印:
f() g()
具体地说,我的目的是获取这些代码并从中创建一个函数。所以我可以做:with runInThreads()或with runManyTimesTillSuccess(),。。在
with runInThreads()
with runManyTimesTillSuccess()
下面是如何使用带参数的修饰符:
>>> 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()
它给出了:
因此,您可以轻松做到:
any code... @runInThreads def _(): whatever...
您甚至可以在函数中定义_任意次数。在
_
附言:我从withhacks读了link,然后想到了这一点,并想在那里发表评论,只是注意到comments there中已经提出了相同的技术。在
下面是如何使用带参数的修饰符:
但是,withhacks模块提供了几个特定于CPython的黑客行为的例子,让你做各种创造性的事情。在
不过,Python的官方代码块和生成器仍在使用。在
你为什么不找个装修工?在
我刚试过(我这里还有Python2.6.4,但它肯定也能用在较新的版本上)
它给出了:
^{pr2}$因此,您可以轻松做到:
您甚至可以在函数中定义
_
任意次数。在附言:我从withhacks读了link,然后想到了这一点,并想在那里发表评论,只是注意到comments there中已经提出了相同的技术。在
相关问题 更多 >
编程相关推荐