问题
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