我有以下两种方法来设置对象中参数的默认值: 第一个:
class Test():
Weight = 12.5
def __init__(self, weight = Weight):
self.weight = weight
Testing = Test()
print("First testing: {}".format(Testing.weight))
第二个是:
class Test2():
Weight = 12.5
def __init__(self, weight = None):
if weight is None:
self.weight = Test2.Weight
Testing2 = Test2()
print("Second testing: {}".format(Testing2.weight))
这两个结果的预期格式,他们将打印12.5。 我的问题是,这些方法是否等效,其中一种方法是否比另一种方法更快(我个人的建议是,第一种方法执行起来时间更短)?你喜欢哪一个?还有其他更好的方法吗? 非常感谢
这两种方法不完全相同。在第一个示例中,
Test(None)
将导致将weight
设置为None
,而在第二个示例中,它将导致将weight
设置为Weight
除此之外,我更喜欢第一种方法,特别是如果很明显需要浮点数的话。只是没那么好写。但是,如果您必须避免将
weight
设置为None
,那么两者的结合可能是最佳选择关于速度:我不在乎第二种方法会花费多少纳秒
编辑:正如其他答案所指出的,如果您更新
Test.Weight
,默认参数将不会得到更新,但在第二个示例中,您将始终设置更新的值。如果这是一个问题,使用第二种方法如果
<class>.weight
得到更新,则它们不是:默认参数在方法创建时被求值一次,因此在第一种情况下,默认参数将保持
12.5
,无论Test1.weight
发生什么请参阅this topic,了解有关默认参数求值的讨论
def __init__(self, weight = Weight)
将只在函数定义时计算一次,而Test.Weight
将每次计算一次。所以在这种情况下,你会看到不同的结果:相关问题 更多 >
编程相关推荐