在Python中如何区分未赋值变量和零?
某些外部代码运行以下代码的my函数:在Python中如何区分未赋值变量和零?,python,python-2.7,unassigned-variable,Python,Python 2.7,Unassigned Variable,某些外部代码运行以下代码的my函数: def __init__(self,weights=None,threshold=None): print "weights: ", weights print "threshold: ", threshold if weights: print "weights assigned" self.weights = weights if threshold: print "th
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
即,打印操作符的行为类似于阈值为零,而if
操作符的行为类似于未定义
正确的解释是什么?发生了什么事?阈值
参数的状态是什么以及如何识别它?如果权重不是无,则使用而不是如果权重
更多细节:当你说if weights
时,你要求Python在布尔上下文中计算weights
,许多事情可能是“假等价”(或“假等价”),包括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
我不知道你在问什么<在Python的布尔上下文中,code>0
为false。因此,对于threshold
,它们将传递零。结果中分配给self.threshold的是什么?Python中没有未定义的变量。我猜您的意思是threshold=None
表示未定义,但如果没有给出参数,则意味着threshold
是默认分配的None
。None
和0
都被视为False
。因为如果阈值
的计算结果不为true,那么什么是“Nothing”?是否与None
相同?if not weights==None:
与if weights!=无
?此外,您还可以测试type()
,尽管这不是很像python。您通常应该对None
使用标识比较,而不是相等。(即,是None
或不是None
而不是=
和!=
。你是对的。我修正了答案。谢谢!