python random.choice报错_Python – AttributeError: 'module' object has no attribute 'choice'错误怎么解决?...
最新推荐文章于 2024-08-15 15:46:55 发布
最新推荐文章于 2024-08-15 15:46:55 发布 阅读量 2.7k

Traceback (most recent call last):

File "random.py", line 4, in import random

File "/root/random.py", line 5, in print random.choice("aflskdjf")

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

‘module’ object has no attribute ‘choice’意思就是模块中没有’choice’属性。仔细核对了python lib库中的random.py,没有问题啊?!

研究了半天才发现是文件命名的问题.大家注意我的文件名/root/random.py,跟lib库中的random模块重名,所以import random的时候,python首先把我写的上面的代码导入了,而不是lib库中的random.py。在我写的/root/random.py肯定找到不到choice属性。修改文件名就搞定了。比如改成/root/rand.py

正常输出:

[root@localhost ~]# python rand.py

有人可以告诉我我可能做错了什么。 当我运行 python 代码时,我一直收到此消息:1234567import random foo = ['a', 'b', 'c', 'd', 'e'] random _item = random . cho ice (foo)print random _item 错误 AttributeError : ' module ' object has no attribute ' cho ice '你... 在 Python 中,如果你尝试调用一个函数,但该函数没有被定义,你可能会遇到“ AttributeError : function object has no attribute 错误 python 在执行程序的时候发现 报错 AttributeError : module ‘numpy. random ’ has no attribute ‘default_rng’,如下: 这类 报错 一般情况下是因为numpy模块的版本引起的,用pip install查看一下,发现我这里的numpy版本是1.15.4 需要吧numpy模块的版本更新到1.17以上才可以