简体   繁体   English

模块“随机”没有属性“随机”

[英]module 'random' has no attribute 'random'

I have read some other questions from stackoverflow, all they need to do it change file name to something else, but my file name is different already:我已经从stackoverflow阅读了一些其他问题,他们需要做的就是将文件名更改为其他内容,但我的文件名已经不同了:

import random

x = random.random()

print(x)

and I got error like:我得到了如下错误:

Traceback (most recent call last):
  File "math.py", line 1, in <module>
    import random
  File "/anaconda3/lib/python3.6/random.py", line 42, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  File "/Users/pgao/Documents/Python Project/math.py", line 3, in <module>
    x = random.random()
AttributeError: module 'random' has no attribute 'random'

please help me with this simply question, i am selfstudy python language recently.请帮我解决这个简单的问题,我最近正在自学 python 语言。 thanks.谢谢。

The problem is that the random module imports the math module, and since you named your own source file math.py it's what will be imported.问题是random模块导入了math模块,并且由于您将自己的源文件命名为math.py ,因此它将被导入。

Rename your source file to something else.将源文件重命名为其他名称。

On the contrary, you've managed to shoot yourself in the foot by naming your file not random.py but math.py , which is also a builtin, and which random imports.相反,通过将文件命名为不是random.py而是math.py (它也是一个内置的,并且random导入),您已经成功地击中了自己的脚。

The traceback is exactly correct (thanks for including it.).回溯是完全正确的(感谢包含它。)。 When random tries to figure out what it is defined as, it imports math , which resolves to your original file.random试图找出它的定义时,它会导入math ,它会解析为您的原始文件。 Your original file then tries to figure out what it is (again), but there is a placeholder for random (only 42 lines are evaluated so far), and it doesn't have any random.random attribute.然后,您的原始文件(再次)尝试弄清楚它是什么,但是有一个random占位符(到目前为止只评估了 42 行),并且它没有任何random.random属性。

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

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