Python bool type

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.