When you have code like this:
class Counter:
def __init__(self):
self.count = 0
def incrementor(c, num):
c.count += 1
num += 1
def main():
counter = Counter()
num = 0
incrementor(counter, num)
return (counter.count, num)
print(main())
What is actually happening at the call site: incrementor(counter, num)
is this:
WARNING: PSEUDO CODE AHEAD
counter = Counter()
num = 0
c = counter
num = num
call incrementor
The above is bizarre and easy to misunderstand, so I'll rephrase it:
WARNING: PSEUDO CODE AHEAD
def incrementor(c, n):
c.count += 1
n += 1
counter = Counter()
num = 0
c = counter
n = num
call incrementor
Now where I have put n = num
the n
is the name of the variable used inside incrementor()
, which shows n
is a different variable, which gets incremented inside the function, but thrown away when it returns.
So, in order to do what it seems you want to do you need to do this:
class Counter:
def __init__(self):
self.count = 0
def incrementor(c, num):
c.count += 1
return num + 1
def main():
counter = Counter()
num = 0
for x in range(0, 100):
num = incrementor(counter, num)
return (counter.count, num)
print(main())
Output:
(100, 100)