Python allows developers to customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible
to define an object’s own truthiness or falsiness by overriding __bool__
method. It is invoked when the built-in bool()
function is called on the object. The bool()
function returns True
or False
based on the truth value of the
object.
The Python interpreter will call these methods when performing the operation they’re associated with. Each special method expects a specific return
type. Calls to a special method will throw a TypeError
if its return type is incorrect.
An issue will be raised when one of the following methods doesn’t return the indicated type:
-
__bool__
method should return bool
-
__index__
method should return integer
-
__repr__
method should return string
-
__str__
method should return string
-
__bytes__
method should return bytes
-
__hash__
method should return integer
-
__format__
method should return string
-
__getnewargs__
method should return tuple
-
__getnewargs_ex__
method should return something which is of the form tuple(tuple, dict)