Python错误“str”对象没有属性“choice”

scr*_*111 0 python random attributes

所以,我有这个代码:

import random, string, os, time
a = 0
random = ''
def calcular():
    global random
    random = ''.join([random.choice(string.ascii_letters) for n in xrange(4)])
    print random
while a<1:
    calcular()
    a=a+1
    pass
print time.strftime('%H:%M:%S')
os.system('pause')
Run Code Online (Sandbox Code Playgroud)

但我得到了

AttributeError: 'str' object has no attribute 'choice'
Run Code Online (Sandbox Code Playgroud)

有什么问题?

Dan*_*iel 6

random您正在覆盖以具有相同变量名的字符串命名的模块。最好不要为字符串使用其他名称。

import random, string, time

def calcular():
    letters = ''.join(random.choice(string.ascii_letters) for n in xrange(4))
    print letters

a = 0
while a<1:
    calcular()
    a += 1
print time.strftime('%H:%M:%S')
Run Code Online (Sandbox Code Playgroud)