if statement without a condition

前端 未结 3 646
余生分开走
余生分开走 2020-12-11 03:10
def f1(x,y):
      if x:    
          x = [1,2,3]
          x.append(4)
      else:
          x = 2
      return x + y

L1 = [1,2,3]
L2 = [55,66]
L3 = []
y = 3
prin         


        
3条回答
  •  囚心锁ツ
    2020-12-11 03:56

    Your if statement is equivalent to if bool(x): ... where Python first tries to look for a __nonzero__ method on x (__bool__ in Python 3) and if it cannot find it returns True per default unless x is None, False, has a __len__ method that returns zero, is an empty mapping or a numeric type with value zero.

    Some examples:

    >>> class A(object):
    ...     pass
    ... 
    >>> bool(A())
    True
    >>> class B(object):
    ...     def __nonzero__(self): return False
    ... 
    >>> bool(B())
    False
    >>> class C(object):
    ...     def __len__(self): return 0
    ... 
    >>> bool(C())
    False
    >>> class D(object):
    ...     def __len__(self): return 0
    ...     def __nonzero__(self): return True
    ... 
    >>> bool(D())
    True
    

提交回复
热议问题