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

2024-04-25 04:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的第一次尝试:

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新手,我不知道,但是我觉得我的recursion概念看起来很混乱


Tags: ofidstringreturnifdefcheckcreate
2条回答

第二种方法是返回a generate\u 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

相关问题 更多 >