Python random function

前端 未结 9 1138
后悔当初
后悔当初 2020-12-10 03:26

I\'m having problems with Python\'s import random function. It seems that import random and from random import random are importing different thing

9条回答
  •  长情又很酷
    2020-12-10 04:08

    If you are using PyDev or other clever IDE, make sure it did not import the module automatically, overriding your import. It can be especially confusing here, when module name is equal to a function name, because the error thrown is not a NameError. In my case I added

    import random
    

    and later used it:

    r = random.radom()
    

    but got:

    AttributeError: 'builtin_function_or_method' object has no attribute 'random'
    

    Only after searching I found that PyDev automatically added the line

    from random import random
    

    to the end of my imports, so I was in fact calling attribute random of method random. Solution is to delete the automatic import or use it and call the random() method directly.

提交回复
热议问题