Python函数默认参数随机值 [英] Python function default argument random value

查看:38
本文介绍了Python函数默认参数随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,将按预期生成一个随机值:

In the following code, a random value is generated as expected:

import random

for i in range(10):
    print(random.randint(0,10))

但是,如果我使用函数,这将不起作用:

However, this does not work if I use a function:

import random

def f(val: int = random.randint(0,10)):
    print(val)

for i in range(10):
    f()

第二个代码段的结果为什么总是相同的数字?我能找到的最相似的问题是这个一个,但是它指的是另一种语言(我不精通).

Why is the result of the second code snippet always the same number? The most similar question I could find is this one, but it refers to a different language (I don't master) .

推荐答案

当您调用函数时不评估默认参数表达式,而当您 create 时评估默认参数表达式功能.因此,无论您做什么,都将始终获得相同的价值.

The default argument expression isn't evaluated when you call the function, it's evaluated when you create the function. So you'll always get the same value no matter what you do.

解决此问题的典型方法是使用一个标志值并将其替换在函数体内:

The typical way around this is to use a flag value and replace it inside the body of the function:

def f(val=None):
    if val is None:
        val = random.randint(0,10)
    print(val)

这篇关于Python函数默认参数随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆