增量函数如何不增加数字变量?

How incrementor function is not incrementing the num variable?

我无法理解请帮助我。我只想知道为什么 num 变量在调用函数增量器时不递增?我猜输出应该是 (100,100),而不是显示 (100,0)

def main():
    counter=Counter()
    num=0
    for x in range(0,100):
        incrementor(counter,num)
    return (counter.count, num)
def incrementor(c, num):
    c.count+=1
    num+=1

class Counter:
    def __init__(self):
        self.count=0

print(main())

当你有这样的代码时:

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())

呼叫站点实际发生的情况:incrementor(counter, num) 是这样的:

警告:前方有伪代码

counter = Counter()
num = 0

c = counter
num = num

call incrementor

上面的内容比较离奇,容易让人误解,所以我改一下:

警告:前方有伪代码

def incrementor(c, n):
    c.count += 1
    n += 1

counter = Counter()
num = 0

c = counter
n = num

call incrementor

现在我放 n = num 的地方 nincrementor() 中使用的变量的名称,这表明 n 不同的 变量,在函数内部递增,但在 returns.

时被丢弃

所以,为了做你想做的事,你需要这样做:

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())

输出:

(100, 100)