问题
Possible Duplicate:
Why can’t Python handle true/false values as I expect?
Seems a stupid question, but why is the following statement in Python not explicitly forbidden?
>> True=False
>> True
False
How is True
and False
handled by Python interpreter?
回答1:
True
, just like str
or any other builtin, is just a name that exists in the scope by default. You can rebind it like any other such name.
回答2:
Python actually has very few reserved words. All the rest are subject to redefinition. It's up to you to be careful!
回答3:
>>> True = False
False
In the above assignment, True
is just a variable like any other variable you use.
Its scope is limited to the current scope. So you can assign any values to it like in the below example. Note that the comparison 2 < 3
still prints True
, because you have still access to builtin
.
>>> True = 3
>>> True
3
>>> 2 < 3
True
回答4:
Typing
True = False
you create a new variable called True, which value you assign to False.
Answering your second question, True and False are customized versions of integers 1 and 0 (technically speaking, subclasses), which just have a different string representation.
来源:https://stackoverflow.com/questions/13401563/true-false-assignment-in-python-2-x