Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:这个局部变量是静态的吗?_Python_Django_Recursion - Fatal编程技术网

Python:这个局部变量是静态的吗?

Python:这个局部变量是静态的吗?,python,django,recursion,Python,Django,Recursion,我的第一次尝试: def generate_id(): """ Create unique id of alphanumeric characters """ i = 0 id = '' while i!=10: id = id + random.choice(string.ascii_letters + string.digits) i+=1 if check_unique(id): return

我的第一次尝试:

def generate_id():

    """ Create unique id of alphanumeric characters """
    i = 0
    id = ''
    while i!=10:
        id = id + random.choice(string.ascii_letters + string.digits)
        i+=1

    if check_unique(id):
           return id 

    id = generate_id()
    return id


def check_unique(id):
    """Check if id is unique"""
    try:
        instances = SomeModel.objects.get(id=id)
    except ObjectDoesNotExist:
        return True

    return False
第二种方式:

def generate_id():

    """ Create unique id of alphanumeric characters """
    i = 0
    id = ''
    while i!=10:
        id = id + random.choice(string.ascii_letters + string.digits)
        i+=1

    if check_unique(id):
           return id 

    generate_id()



def check_unique(id):
    """Check if id is unique"""
    try:
        instances = SomeModel.objects.get(id=id)
    except ObjectDoesNotExist:
        return True

    return False
如果我以第二种方式进行操作,我生成唯一id的逻辑不会出错吗?因为我可能会丢失上次通话的身份证


我是python新手,我不知道,但我认为我的
递归
概念看起来很混乱

第二种方法是在generate_id函数的末尾返回一个值:

return generate_id()
我还建议进行迭代而不是递归调用。。。在这种情况下似乎更干净。

遵循您的代码:

if check_unique(id):  # If this is `false`, you keep going
    return id 

generate_id()  # Now what? You call the function. Nothing gets returned.
如果要创建唯一的ID,请不要使用递归。只要使用
while
循环并生成新ID,只要它们不是唯一的:

characters = string.ascii_letters + string.digits

def generate_id(length=10):
    return ''.join(random.choice(characters) for i in range(length))

def generate_unique_id(length=10):
    id = generate_id(length)

    while not check_unique(id):
        id = generate_id(length)

    return id