如果您想在循环之前进行零初始化,您可以使用带计数器的Singleton :while
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
cls.count=0
else:
cls.count+=1
return cls._instance
那么将只有一个 Singleton 实例,并且每个额外的实例只会添加一个:
>>> Singleton().count # initial instance
0
>>> Singleton().count
1
>>> Singleton().count
2
>>> Singleton().count
3
然后你的while循环变成:
while Singleton():
x=int(raw_input('x: '))
if x>10: break
print 'While loop executed',Singleton().count,'times'
输入1,2,3,11
它会打印:
x: 1
x: 2
x: 3
x: 11
While loop executed 4 times
如果您不介意在循环之前进行单行初始化while
,则可以子类化一个 interator:
import collections
class WhileEnum(collections.Iterator):
def __init__(self,stop=None):
self.stop=stop
self.count=0
def next(self): # '__next__' on Py 3, 'next' on Py 2
if self.stop is not None:
self.remaining=self.stop-self.count
if self.count>=self.stop: return False
self.count+=1
return True
def __call__(self):
return self.next()
然后你的while循环变成:
enu=WhileEnum()
while enu():
i=int(raw_input('x: '))
if i>10: break
print enu.count
我认为第二种方法要好得多。您可以有多个枚举器,还可以设置循环次数的限制:
limited_enum=WhileEnum(5)