简体   繁体   English

每次在脚本中获取一个随机数

[英]Getting a random number each time in a script

I'm having trouble with the following bit of code: 我在以下代码方面遇到麻烦:

from random import randint
class character():
    __init__(self):
        #init stuff here
    def luck(self, Luck = randint(0, 3)):
        return Luck

I have to call this method multiple times in my script, for multiple instances, to get a different number each time. 我必须在脚本中多次调用此方法(对于多个实例),才能每次获得一个不同的数字。 The problem that I'm having is that whenever i call this method, no matter from what instance, I always to get the same result. 我遇到的问题是,无论何时从哪个实例调用此方法,我总是得到相同的结果。 For example, in the following code: 例如,在以下代码中:

Foo = character()
Bar = character()
for foobar in range(3):
    print(Foo.luck(), Bar.luck())

I'd get as my output: 我会得到我的输出:

1 1
1 1
1 1

By the way, in my code, I used randint(0, 3) as an argument for the luck() method because, in some specific situations, I'd like to assign values to it myself. 顺便说一下,在我的代码中,我将randint(0, 3)用作luck()方法的参数,因为在某些特定情况下,我想自己为其分配值。

Back to the point, how can I get a different number each time? 回到要点,每次如何获得一个不同的数字?

This is a definition for the luck function. 这是运气函数的定义。 If the user specifies a number it will be returned. 如果用户指定一个数字,它将被返回。 If instead no argument is given, Luck will be set from randint and that random value returned. 如果没有给出任何参数,那么将从randint设置randint并返回该随机值。

def luck(self, Luck = None):
    if Luck is None:
        Luck = randint(0,3)
    return Luck

In python, the default expressions that set the default values for function arguments are only executed once. 在python中,设置函数参数默认值的默认表达式仅执行一次。 This means that once you define the luck method, whatever value randint() spit out the first time will stay for all invocations. 这意味着,一旦您定义了luck方法,无论第一次调用randint()randint() ,所有调用都将保留。

To get a new random number every time the method is called, you need to call it inside the body of the method: 为了在每次调用该方法时获得一个新的随机数,您需要在方法主体内部调用它:

class Character(object):
    @staticmethod # required if you're not accepting `self`
    def luck():
        return randint(0, 3)

This will work as expected. 这将按预期工作。

You can use None or something for a default argument, check if you got None and if you did - call randint() (if not just return what you did get). 您可以使用None或其他方式作为默认参数,检查是否获得None以及是否获得-调用randint() (如果不返回所获得的结果)。
If you use randint() in the function deceleration it will randomize it only once. 如果在函数减速中使用randint() ,它将仅随机化一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM