如何在Python中区分未分配的变量?

时间:2016-06-19 15:04:21

标签: python python-2.7 unassigned-variable

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

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参数的状态是什么以及如何识别它?

2 个答案:

答案 0 :(得分:5)

使用if weights is not None代替if weights

更多详细信息:当您说if weights时,您要求Python在布尔上下文中评估weights,并且许多内容可以是“false-equivalent”(或“falsy”),包括{{ 1}},空字符串,空容器等。如果您只想检查0值,则必须明确地执行此操作。

答案 1 :(得分: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