求助,为什么 randint()方法作为一个形式参数,然后进行 for 循环调用的时候每次都 random 同一个数出来

2018-11-12 10:29:49 +08:00
 Alerta
# -*- coding:utf-8 -*-
import random
import collections
result = {
    1: 0,
    2: 0,
    3: 0,
    4: 0,
}


def test(b=random.randint(1, 5)):
    global result
    if b == 1:
        result[1] += 1
    elif b == 2:
        result[2] += 1
    elif b == 3:
        result[3] += 1
    elif b == 4:
        result[4] += 1


if __name__ == "__main__":
    for i in range(1000):
        test()

    print(result)
{1: 1000, 2: 0, 3: 0, 4: 0}

每次都只是不同的一个数字跑 1000 遍,感觉像是 list 作为形参的时候,可变对象的问题。但是 randint 本身打印出来就是一个 int 类型,求助大佬指教指教

1809 次点击
所在节点    Python
8 条回复
xpresslink
2018-11-12 10:33:41 +08:00
你这么写
def test(b=random.randint(1, 5)):
等同于
b=random.randint(1, 5)
def test(b):
Alerta
2018-11-12 10:42:39 +08:00
@xpresslink 我也是这样改的,但就是想知道为啥,求指教
ChristopherWu
2018-11-12 10:47:33 +08:00
@Alerta

debug 路径是这样子的:

这个程序跟其他程序有什么区别-> 用了默认参数 -> 不用默认参数显式传程序就没有问题 -> 查查 python 默认参数 是怎么样做的 -> https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001374738449338c8a122a7f2e047899fc162f4a7205ea3000 -> Python 函数在定义的时候,默认参数 L 的值就被计算出来了 -> 所以 def test(b=random.randint(1, 5))的函数原型是 def test(b=一跑完这个函数定义后取到的 1-5 的随机值) -> 所以你每次调默认参数都是固定的。

问题解决。
no1xsyzy
2018-11-12 10:48:23 +08:00
def 的时候默认值就计算完毕了,会永久存储
比如
def pusher(item, tow=[]):
tow.append(item)
return tow
pusher(1)
pusher(2)
jheroy
2018-11-12 10:50:19 +08:00
Python ’ s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
no1xsyzy
2018-11-12 10:50:47 +08:00
Alerta
2018-11-12 11:27:12 +08:00
@ChristopherWu 真的很感谢,不仅仅是感谢提供的答案,更重要的是提供了解决问题的思路,真的很棒
Alerta
2018-11-12 11:27:26 +08:00
@no1xsyzy 感谢感谢 明白了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/506891

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX