Python 'module' 对象没有属性 'choice' - 尝试使用 random.choice

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25695412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:30:16  来源:igfitidea点击:

'module' object has no attribute 'choice' - trying to use random.choice

pythonattributeerror

提问by AMHD

Could someone please tell me what I may be doing wrong. I keep getting this message when I run my python code:

有人可以告诉我我可能做错了什么。运行 python 代码时,我不断收到此消息:

import random

foo = ['a', 'b', 'c', 'd', 'e']

random_item = random.choice(foo)

print random_item

Error

错误

AttributeError: 'module' object has no attribute 'choice'

AttributeError: 'module' 对象没有属性 'choice'

回答by Adam Smith

Sounds like an import issue. Is there another module in the same directory named random? If so (and if you're on python2, which is obvious from print random_item) then it's importing that instead. Try not to shadow built-in names.

听起来像是导入问题。同一个目录中是否有另一个名为 的模块random?如果是这样(如果你在 python2 上,这很明显来自print random_item),那么它会导入它。尽量不要隐藏内置名称。

You can test this with the following code:

您可以使用以下代码对此进行测试:

import random

print random.__file__

The actual random.pymodule from stdlib lives in path/to/python/lib/random.py. If yours is somewhere else, this will tell you where it is.

random.pystdlib 中的实际模块位于path/to/python/lib/random.py. 如果你的在其他地方,这会告诉你它在哪里。

回答by Cory Kramer

Shot in the dark: You probably named your script random.py. Do not name your script the same name as the module.

在黑暗中拍摄:您可能将脚本命名为random.py。不要将您的脚本命名为与模块相同的名称。

I say this because the randommodule indeed has a choicemethod, so the import is probably grabbing the wrong (read: undesired) module.

我这样说是因为random模块确实有一个choice方法,所以导入可能是抓取了错误的(阅读:不需要的)模块。

回答by James

In short, Python's looking in the first file it finds named "random", and isn't finding the choice attribute.

简而言之,Python 正在查找它找到的第一个名为“random”的文件,并没有找到选择属性。

99.99% of the time, that means you've got a file in the path/directory that's already named "random". If that's true, rename it and try again. It should work.

99.99% 的情况下,这意味着您在路径/目录中有一个已命名为“随机”的文件。如果这是真的,请重命名并重试。它应该工作。

回答by Trevor

I also got this error by naming a method randomlike this:

我也通过命名这样的方法得到了这个错误random

import random

def random():

  foo = ['a', 'b', 'c', 'd', 'e']

  random_item = random.choice(foo)

  print random_item

random()

It's not your case (naming a file random.py) but for others that search about this error and may make this mistake.

这不是您的情况(命名文件random.py),而是其他搜索此错误并可能犯此错误的人。

回答by tyan

for me the problem is I use

对我来说,问题是我使用

random.choices 

in python 3.6 local dev but the server is python3.5 don't have this method...

在python 3.6本地开发但服务器是python3.5没有这个方法...