函数参数中的python UUID4

时间:2017-08-09 18:27:04

标签: python python-2.7

     def __init__(self, unique_id=uuid.uuid4())

如果用户没有指定,我希望我实例化的每个对象都有不同的ID。当我实例化几个类时,它们都具有相同的UUID。我可以对这里发生的事情进行技术概述,以便我可以更好地理解Python函数和初始化器吗?

2 个答案:

答案 0 :(得分:2)

我相信它会使你的代码更清晰,如果你只是将它添加到方法体中,例如:

def __init__(self, unique_id=None):
    if not unique_id:
        unique_id = uuid.uuid4()

更紧凑的版本是:

def __init__(self, unique_id=None):
    unique_id = uuid.uuid4() if not unique_id else unique_id

如果需要,这将允许您覆盖unique_id

答案 1 :(得分:2)

您提出的代码存在的问题是默认参数仅评估一次(导入模块时),请参阅例如"Least Astonishment" and the Mutable Default Argument

为了解决这个问题,你应该遵循使用None作为“不是由用户提供”的标志的惯用语,如下所示:

def __init__(self, unique_id=None):
    if unique_id is None:
        unique_id = uuid.uuid4()