The difference between the __bool__ method in Python2 and Python3 is described in detail

  • 2021-01-19 22:17:34
  • OfStack

When learning Python object-oriented programming, encountered a very interesting small problem. The __bool__ method of Python does not work.

I read and reread the tutorial in my hand and made sure that the code I wrote should work. The __bool__ method I implemented does not appear to be an interface to Python itself.

The code is as follows:


class Demo():

def __init__(self,value = 0):

  self.value = value

def __bool__(self):

  return bool(self.value > 5)


obj = Demo()

obj.value = 0

if obj:

print("yes")

else:

print("no")

print(bool(obj))

These days the use of Win10 below the bash with more comfortable, I will 1 straight in this environment for program debugging.

The results of the test are as follows:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08/16$python bool_demo.py

yes

True

It was somewhat strange, not exactly what I had expected. After trying to call the bool method directly and finding it doesn't exist, I guess this is probably a point of difference between ES21en2 and ES22en3. Win10 Linux subsystem python version is 2. X, specific as follows:


grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08/16$python -V

Python 2.7.6

Python version 3.X version 3. CMD version 3. CMD version 3.X version 3.


E:\01_workspace\02_programme_language\03_python\03_OOP\2017\08\16>pythonbool_demo.py

no

False


E:\01_workspace\02_programme_language\03_python\03_OOP\2017\08\16>python-V

Python 3.6.0

The final result is in line with expectations!

It looks like this should be a 1-point interface difference between Python3 and Python2. If from the point of view of easy to use, it is natural that Python3 with this interface is more user-friendly 1. This gives programmers more freedom and enables them to implement code that is more integrated with Python itself.


Related articles: