Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
In Python, each value has a boolean value. It is implicitly cast when you use if, bool, not etc. False objects are None, False, 0 of any type, and empty collections: "", [], {} etc., including custom collections with the __len__ method as long as __len__ returns 0. You can also define custom truth value testing for your objects, the __bool__ magic method is there for this: class Rectangle: def __init__(self, width, height): self._w = width self._h = height def __bool__(self): return bool(self._w and self._h) In : bool(Rectangle(2, 3)) Out: True In : bool(Rectangle(2, 0)) Out: False In : bool(Rectangle(0, 2)) Out: False Mind, that __bool__ is called __nonzero__ in Python 2.