'module' object has no attribute 'choice' - trying to use random.choice

后端 未结 5 1205
挽巷
挽巷 2020-12-31 00:48

Could someone please tell me what I may be doing wrong. I keep getting this message when I run my python code:

import random

foo = [\'a\', \'b\', \'c\', \         


        
相关标签:
5条回答
  • 2020-12-31 01:00

    I also got this error by naming a method random like this:

    import random
    
    def random():
    
      foo = ['a', 'b', 'c', 'd', 'e']
    
      random_item = random.choice(foo)
    
      print random_item
    
    random()
    

    It's not your case (naming a file random.py) but for others that search about this error and may make this mistake.

    0 讨论(0)
  • 2020-12-31 01:06

    for me the problem is I use

    random.choices 
    

    in python 3.6 local dev but the server is python3.5 don't have this method...

    0 讨论(0)
  • 2020-12-31 01:14

    In short, Python's looking in the first file it finds named "random", and isn't finding the choice attribute.

    99.99% of the time, that means you've got a file in the path/directory that's already named "random". If that's true, rename it and try again. It should work.

    0 讨论(0)
  • 2020-12-31 01:16

    Shot in the dark: You probably named your script random.py. Do not name your script the same name as the module.

    I say this because the random module indeed has a choice method, so the import is probably grabbing the wrong (read: undesired) module.

    0 讨论(0)
  • 2020-12-31 01:17

    Sounds like an import issue. Is there another module in the same directory named random? If so (and if you're on python2, which is obvious from print random_item) then it's importing that instead. Try not to shadow built-in names.

    You can test this with the following code:

    import random
    
    print random.__file__
    

    The actual random.py module from stdlib lives in path/to/python/lib/random.py. If yours is somewhere else, this will tell you where it is.

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