I used to write C # code. When I want to convert a string 'false' to the bool type, I naturally wrote the following Python code:
Have you seen the above results? Is True. Suddenly remember that in Python, except ''," ", 0, (), [], {}, and None are False, all others are True. That is to say, the above 'false' is a non-null string, so the result is True.
To get a better understanding of the Python bool type, I have read the following instructions:
>>> Help (True)
Help on bool object:
Class bool (int)
| Bool (x)-> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| Bool
| Int
| Object
|
| Methods defined here:
|
| _ And __(...)
| X. _ and _ (y) <=> x & y
|
| _ Or __(...)
| X. _ or _ (y) <=> x | y
We can see that bool is a subclass of int, and it cannot be subclass:
Because bool is a subclass of int, 1 indicates True, 0 indicates False:
We can see that the above 2 = True is false. But let's look at the following code:
We can see that "True" is printed out. I think this is because the if statement will call the bool () method internally:
Because bool is inherited from the int type, I guess it will be converted to 0 and 1 for comparison in the end, just like:
(Note: This is just a conjecture, unconfirmed)
Since bool is inherited from the int type, it is natural that the bool type supports mathematical operations:
Finally, I can think of the following to determine whether the string has 'false:
I wonder if there is a better way?