简体   繁体   中英

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:

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. 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.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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