Why do function objects evaluate to True in python?

。_饼干妹妹 提交于 2019-12-02 06:54:26

问题


In python it is valid to make a construction like:

def a(): 
    return 0

if a: 
    print "Function object was considered True"
else:  
    print "Function object was considered False"

I wish to ask what is the logic that a function pointer is evaluated to True.

Why was this kind of construction inserted in the language?


回答1:


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.




回答2:


The rules for evaluating "truthiness" are in the Python documentation chapter on Truth Value Testing.

Note in particular that

All other values are considered true — so objects of many types are always true.

In conclusion; function objects are always true.




回答3:


A list of objects that are False in python:

  • None
  • []
  • {}
  • empty set
  • empty frozenset
  • False
  • 0
  • 0.0
  • 0L
  • 0j
  • empty defaultdict
  • Classes that have implemented __nonzero__() method and that returns a falsy value otherwise __len__() is called. In python 3x __bool__() replaced __nonzero__().


来源:https://stackoverflow.com/questions/12697338/why-do-function-objects-evaluate-to-true-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!