如何区分python中的无分配变量和零变量



一些外部代码运行我的函数以下代码:

def __init__(self,weights=None,threshold=None):
    print "weights: ", weights
    print "threshold: ", threshold
    if weights:
        print "weights assigned"
        self.weights = weights
    if threshold:
        print "threshold assigned"
        self.threshold = threshold

和此代码输出:

weights:  [1, 2]
threshold:  0
weights assigned

即。打印操作员的行为像 threshold一样为零,而 if操作员的行为与未定义一样。

正确的解释是什么?怎么了?threshold参数的状态是什么?

使用if weights is not None代替if weights

更多详细信息:当您说if weights时,您要在布尔上下文中评估python评估 weights,并且许多事情都可以是" false-quervivalent"(或" falsy"),包括0,空字符串,空容器,等等。如果您只想检查None值,则必须明确执行此操作。

您可以明确测试None值。

def __init__(self,weights=None,threshold=None):
    print "weights: ", weights
    print "threshold: ", threshold
    if weights is not None:
        print "weights assigned"
        self.weights = weights
    if threshold is not None:
        print "threshold assigned"
        self.threshold = threshold

相关内容

  • 没有找到相关文章

最新更新