-1

一部の外部コードは、次のコードの機能を実行します。

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

つまり、 print 演算子はthresholdis zero のifように動作しますが、演算子は定義されていないかのように動作します。

正しい解釈は?何が起こっている?パラメータの状態thresholdとその認識方法を教えてください。

4

2 に答える 2

5

if weights is not Noneの代わりに使用しif weightsます。

詳細:ブール値のコンテキストでif weights評価するように Python に依頼していると言うweightsと、多くのものが "false-equivalent" (または "falsy") になる可能性があり0、 、空の文字列、空のコンテナーなどが含まれます。値についてNoneは、明示的に行う必要があります。

于 2016-06-19T15:06:18.820 に答える
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
于 2016-06-19T15:07:47.550 に答える