一些外部代码运行我的函数以下代码:
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