简体   繁体   中英

python import random issue - AttributeError: 'builtin_function_or_method' object has no attribute

im using python3 and i get this errors:

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

passwordGen =  "".join(choice(characters) for x in range(randint(12, 20)))
NameError: name 'randint' is not defined

This is my code:

import random
from random import uniform, random, choice, sample, randint
somelist = ["temp1"]
randomList = random.choice(somelist)

And:

characters = string.ascii_letters + string.digits
passwordGen =  "".join(choice(characters) for x in range(randint(12, 20)))

I know i have only one item in the list, most of the time i have more then 1 in this specific code i have one

I tried to import random only, and then i added from random, every time i get a different error when i change my imports.

If i do it in my python3 :

>>> a = ["temp1"]
>>> import random
>>> b = random.choice(a)
>>> b
'temp1'

So what is the issue ?

When you do import random this binds the name "random" to the built-in module random (which contains a choice function). However on the next line you do:

from random import uniform, random, choice, sample, randint

Here the from random import random rebinds the name "random" to the function random.random which you just imported. Hence the subsequent random.choice resolves "random" to that function and not the module. Instead you can directly use choice as you did later.

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