2012-04-11 88 views
0

我对python有一点怀疑。如果Python中的语句

x = '' 
if x: 
    print 'y' 

所以,它永远不会打印为 'Y'

如果我这样做:

x = 0 
if x: 
    print 'y' 

然后也将这样做。

那么如果我有'值和0值如何区分如果我只需要考虑0值?

+0

如果你正在评估对0再做如果x == 0 – 2012-04-11 07:31:58

+0

没有它的不仅仅是0.可能会有一些整数更多的值。我只想过滤''值。 – sam 2012-04-11 07:33:00

+0

如果它不仅仅针对0,那么可能使用switch case语句或if if elseif类型语句,如果它们只有少数几个可以满足基本情况? – 2012-04-11 07:45:38

回答

4

这是因为目标函数__nonzero__()__len__()将被用来评估条件。 From the docs

object.__nonzero__(self)

调用,实现真值测试和内置操作bool();应返回FalseTrue或其整数等效值0或1.如果未定义此方法,则调用__len__()(如果已定义),并且如果该对象的结果非零,则认为该对象为真。如果一个类既没有定义__len__()也没有定义__nonzero__(),它的所有实例都被认为是真实的。

通过重载这些,您可以用来为自定义类指定这样的行为。

至于如果条件下,可以确切地要检查什么规定:

if x: # evaluate boolean value implicitly 
    pass 
if x is 0: # compare object identity, see also id() function 
    pass 
if x == 0: # compare the object value 
    pass 

至于隐含布尔评估你的特殊情况:int对象被认为True如果他们是非零; str如果物体长度不为零,则认为物体为True

2
if x != '': 
    print 'y' 

仅工作如果x不是''

3

的Python为评估为假的状态的空迭代(这里字符串)。

如果需要检查,如果值是0明确你不得不说x==0

0

我不是你真正想要什么明确的 - 你的问题的措辞有点混乱 - 但这可能有所启发:

>>> test_values = [0,0.00,False,'',None, 1, 1.00, True, 'Foo'] 
>>> for v in test_values: 
    if (not v) and (v != ''): 
     print "Got a logically false value, %s, which was not the empty string ''" % v.__repr__() 


Got a logically false value, 0, which was not the empty string '' 
Got a logically false value, 0.0, which was not the empty string '' 
Got a logically false value, False, which was not the empty string '' 
Got a logically false value, None, which was not the empty string ''