[英]python import random issue - AttributeError: 'builtin_function_or_method' object has no attribute
im using python3 and i get this errors:我正在使用 python3 并且我收到此错误:
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我知道我在列表中只有一项,大多数时候我在这个特定代码中有超过 1 个我有一个
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 :如果我在我的 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).当您
import random
这会将名称“random”绑定到内置模块random
(其中包含一个choice
函数)。 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.这里
from random import random
将名称“random”重新绑定到您刚刚导入的函数random.random
。 Hence the subsequent random.choice
resolves "random" to that function and not the module.因此,随后的
random.choice
将“随机”解析为该函数而不是模块。 Instead you can directly use choice
as you did later.相反,您可以像稍后那样直接使用
choice
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.