Python random function

前端 未结 9 1094
后悔当初
后悔当初 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:06

    The 'random' module is a package from the python standard library, as well as a function defined in this package.

    Using 'import random' imports the package, which you can then use the function from this package: 'random.random()'. You can use any other function from the 'random' package as well.

    You can also tell python to specifically import only the random function from the package random: 'from random import random'. Then you can only use the function 'random()', and should not specify the package it comes from. However you cannot use any other function from the random package, because they have not been imported if you use 'from random import random'.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 04:17

    If you use from random import random, you must call randint() like so: randint(1,5). If you use import random, you call it like so: random.randint(1,5).

    0 讨论(0)
  • 2020-12-10 04:17

    You have to import the random function, from the random module before you can use it use it

    In [1]: from random import random
    
    In [2]: random()
    Out[2]: 0.5607917948041573
    
    0 讨论(0)
  • 2020-12-10 04:18

    import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.

    Doing the import this way this requires you to use the syntax random.random().

    The random function can also be imported from the module separately:

    from random import random
    

    This allows you to then just call random() directly.

    0 讨论(0)
  • 2020-12-10 04:21

    Well, yes, they import different things. import random imports the random module, from random import random imports the random function from the random module. This is actually a good example of why when designing an API in Python, it's often a good idea to try to avoid naming modules and their members the same thing.

    0 讨论(0)
提交回复
热议问题