【问题标题】:Is there an error in Python 3's random.SystemRandom.randint, or am I using in incorrectly?Python 3 的 random.SystemRandom.randint 是否有错误,或者我使用不正确?
【发布时间】:2015-06-07 23:01:45
【问题描述】:
>>> import random
>>> random.SystemRandom.randint(0, 10)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    random.SystemRandom.randint(0, 10)
TypeError: randint() missing 1 required positional argument: 'b'

虽然os.urandomrandint 像正常的randrange 一样工作,但 SystemRandom 应该提供随机数:

>>> print(random.SystemRandom.randint.__doc__)
Return random integer in range [a, b], including both end points.

在 IDLE 中,当我输入它时会出现一个小弹出建议

`random.SystemRandom.randint(self, a, b)`

我认为这就是原因。我不太擅长使用类和理解它们是如何工作的,但第一个参数似乎是作为self 传递的,而它应该是a。我从来没有真正理解为什么self 在它甚至不是关键字的情况下被使用,以及它应该如何工作,但它通常可以。

我是不是做错了,还是应该在应该做这些事情的时候向 Python 基金会报告?

【问题讨论】:

    标签: python random


    【解决方案1】:

    当错误为“TypeError: randint() missing 1 required positional argument: 'b'”时,这是因为编写代码的人可能混淆了他们的

    random.randint()
    

    和他们的

    random.choice()
    

    希望我能帮上忙:D

    【讨论】:

    • 这可能会帮助人们面临错误(缺少必需的 arg),但请注意,它不是原始问题的直接答案,因为 OP 想知道为什么 random.SystemRandom.randint 需要三个参数而不是他们提供的两个论点
    • 没错,我只是说因为我之前也遇到过同样的问题。
    【解决方案2】:

    random.SystemRandom 是一个类。需要实例化;

    In [5]: foo = random.SystemRandom()
    
    In [6]: foo.randint(0, 10)
    Out[6]: 0
    

    完整的文档字符串给出了提示;

    In [12]: random.SystemRandom.randint?
    Signature: random.SystemRandom.randint(self, a, b)
    Docstring: Return random integer in range [a, b], including both end points.
    File:      /usr/local/lib/python3.4/random.py
    Type:      function
    

    self参数表示这个randintSystemRandom方法

    【讨论】:

      【解决方案3】:

      我想你想要:

      import random
      r = random.SystemRandom()
      print(r.randint(0, 10))
      

      改为。

      这是因为您需要创建random.SystemRandom 类的实例。

      不过,您也可以轻松使用以下内容:

      import random
      random.randint(0, 10)
      

      如果您不需要依赖于操作系统的加密 RNG。

      【讨论】:

      • 在模块级函数上使用SystemRandom 与您是否需要单独的实例无关。 SystemRandom 使用依赖于操作系统的加密 RNG,而 random.randint 仅使用 Mersenne Twister;选择使用哪个取决于您需要的 RNG 强度。
      【解决方案4】:

      rllt 它很容易,只要你知道 tat 所以它应该修复,但是当你不这样做时,tit doens towrk 所以就像 dot 那样做是的

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2016-04-06
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多