-1

一些外部代码运行以下代码的我的功能:

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,如何识别?

4

2 回答 2

5

使用if weights is not None而不是if weights.

更多细节:当您说if weights您要求 Pythonweights在布尔上下文中进行评估时,许多事情可能是“假等价”(或“假”)0,包括空字符串、空容器等。如果您只想检查对于一个None值,你必须明确地这样做。

于 2016-06-19T15:06:18.820 回答
0

您可以显式测试一个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
于 2016-06-19T15:07:47.550 回答