【发布时间】:2019-09-17 21:35:53
【问题描述】:
解决这个问题 我显然根本没有很好地解释,而且似乎没有一个答案符合我的想法。
在下面显示的示例中,我试图创建一个更简洁的循环,最终看起来像l(n)、l*n 或类似的东西。
在所示示例中,代码将打印"hello" 5 次(或我设置的任何值),然后在with 循环中执行代码,这并不意外。
但是,想法是循环显示的代码(在本例中为pass)。如何用 with 语句中编写的代码替换 print("hello")?是否可以?我想这不是应该使用 with 语句的用途,所以有替代方案吗?
class loop:
def __init__(self, loops):
self.loops = loops
def __enter__(self):
for x in range(self.loops):
print("hello")
def __exit__(self, *args):
pass
with loop(5):
pass
编辑: 这是编辑后的代码,因为我认为我没有足够清楚地说明我想要做什么:
class loop:
def __init__(self, loops):
self.loops = loops
def __enter__(self):
pass
def __exit__(self, *args):
pass
with loop(5):
print("This will loop 5 times")
with loop(10):
print("This will loop 10 times")
所以在程序的任何时候,我都可以简单地用任何代码键入底部的两行,它就可以工作了。我可以完成这项工作吗?
【问题讨论】:
-
为什么不
for _ in range(5):? -
覆盖
__nonzero__并执行while loop(5):
标签: python class with-statement