某些外部代码运行以下代码的功能:
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
参数的状态是什么以及如何识别它?
答案 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