Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中如何区分未赋值变量和零?_Python_Python 2.7_Unassigned Variable - Fatal编程技术网

在Python中如何区分未赋值变量和零?

在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

某些外部代码运行以下代码的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 "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
而不是
=
!=
。你是对的。我修正了答案。谢谢!