Reputation: 65
I already asked this question, but I guess I have to clarify, and for that I apologize. Let us consider the most mundane, ultimate noobie while loop.
max_count = 4
count = 0
while count < max_count:
print(count)
count += 1
It obviously prints 0 1 2 3. So, I naively reckon, mayhaps we do it OOP style, as below.
class Foo:
def __init__(self, max_count):
self.max_count = max_count
self.count = 0
def loop(self):
while self.count < self.max_count:
print(self.count)
self.count += 1
A = Foo(4).loop()
and again it obligingly spurts out 0 1 2 3. But then I get greedy and say to myself, what if I don't want to print the data, but just retrieve them for something higher and nobler, say doing a few nested loops. So instead of print in the loop method I do a return as below.
class Foo:
def __init__(self, max_count):
self.max_count = max_count
self.count = 0
def loop(self):
while self.count < self.max_count:
return self.count
self.count += 1
A = Foo(4).loop()
print(A)
And the powers that be reward me with a nice, flat 0. In my uneducated lingua, I would say that the class is 'choking' the loop. Please, enlighten me: Is it even possible to loop inside a class or not. And if yes, please point me in the right direction and I will do the digging. BTW, I would like it to be in OOP mode, since what I really intend to is control a number of stepper motors concurrently. If I try to do it procedurally, that will bring back to my 1988 Pascal, Fortran 77 days, and that is a chalice from which I do not want to drink again. I thank you in advance kind comrades.
Upvotes: 0
Views: 86
Reputation: 2615
The reason your result is 0
is because you are returning from the loop
function before incrementing the value. I assume you intended to print the value? or maybe return it after the loop?
This code:
while self.count<self.max_count:
return self.count
self.count+=1
Should be:
while self.count < self.max_count:
self.count+=1
return self.count
Upvotes: 1