簡體   English   中英

python導入隨機問題 - AttributeError:'builtin_function_or_method'對象沒有屬性

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

我正在使用 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

這是我的代碼:

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

和:

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

我知道我在列表中只有一項,大多數時候我在這個特定代碼中有超過 1 個我有一個

我嘗試僅導入隨機,然后我從隨機添加,每次更改導入時都會出現不同的錯誤。

如果我在我的 python3 中這樣做:

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

那么問題是什么?

當您import random這會將名稱“random”綁定到內置模塊random (其中包含一個choice函數)。 但是在下一行你做:

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

這里from random import random將名稱“random”重新綁定到您剛剛導入的函數random.random 因此,隨后的random.choice將“隨機”解析為該函數而不是模塊。 相反,您可以像稍后那樣直接使用choice

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM