这两种设置默认值的方法相等吗?

2024-09-28 23:34:19 发布

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

我有以下两种方法来设置对象中参数的默认值: 第一个:

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。 我的问题是,这些方法是否等效,其中一种方法是否比另一种方法更快(我个人的建议是,第一种方法执行起来时间更短)?你喜欢哪一个?还有其他更好的方法吗? 非常感谢


Tags: 方法testselfnoneformatinitdeftesting
3条回答

这两种方法不完全相同。在第一个示例中,Test(None)将导致将weight设置为None,而在第二个示例中,它将导致将weight设置为Weight

除此之外,我更喜欢第一种方法,特别是如果很明显需要浮点数的话。只是没那么好写。但是,如果您必须避免将weight设置为None,那么两者的结合可能是最佳选择

关于速度:我不在乎第二种方法会花费多少纳秒

编辑:正如其他答案所指出的,如果您更新Test.Weight,默认参数将不会得到更新,但在第二个示例中,您将始终设置更新的值。如果这是一个问题,使用第二种方法

如果<class>.weight得到更新,则它们不是:

class Test1():
    Weight = 12.5

    def __init__(self, weight = Weight):
        self.weight = weight


testing = Test1()
print("First testing: {}".format(testing.weight))
Test1.Weight = 50
testing2 = Test1()
print("Second testing: {}".format(testing2.weight))

# First testing: 12.5
# Second testing: 12.5


class Test2():
    Weight = 12.5

    def __init__(self, weight = None):
        if weight is None:
            self.weight = Test2.Weight

testing = Test2()
print("First testing: {}".format(testing.weight))
Test2.Weight = 50
testing2 = Test2()
print("Second testing: {}".format(testing2.weight))
# First testing: 12.5
# Second testing: 50

默认参数在方法创建时被求值一次,因此在第一种情况下,默认参数将保持12.5,无论Test1.weight发生什么

请参阅this topic,了解有关默认参数求值的讨论

def __init__(self, weight = Weight)将只在函数定义时计算一次,而Test.Weight将每次计算一次。所以在这种情况下,你会看到不同的结果:

testing = Test()
Test.Weight = 42
testing2 = Test()
print(testing.weight, testing2.weight)

相关问题 更多 >