Why do function objects evaluate to True in python?

前端 未结 4 1423
后悔当初
后悔当初 2020-12-21 17:36

In python it is valid to make a construction like:

def a(): 
    return 0

if a: 
    print \"Function object was considered True\"
else:  
    print \"Funct         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 18:13

    A lot of things evaluate to True in Python. From the documentation on Boolean operators:

    In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

    Functions in Python, like so many things, are objects, and not empty. Thus, in a boolean context, they evaluate to True.

提交回复
热议问题