


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
True and false values. In fact, all objects in Python have a truth value. By default, objects are considered to be true, but the special __bool__ method can be ...
Typology: Slides
1 / 4
This page cannot be seen from the preview
Don't miss anything!
The built-in mathematical operators can be extended in much the same way as repr; there are special method names corresponding to Python operators for arithmetic, logical, and sequence operations.
To make our code more legible, we would perhaps like to use the + and * operators directly when adding and multiplying complex numbers. Adding the following methods to both of our complex number classes will enable these operators to be used, as well as the add and mul functions in the operator module:
Now, we can use infix notation with our user-defined classes.
True and false values. We saw previously that numbers in Python have a truth value; more specifically, 0 is a false value and all other numbers are true values. In fact, all objects in Python have a truth value. By default, objects are considered to be true, but the special bool method can be used to override this behavior. If an object defines the bool method, then Python calls that method to determine its truth value.
As an example, suppose we want the complex number 0 + 0 * i to be false. We can define the bool method for both our complex number implementations.
We can call the bool constructor to see the truth value of an object, and we can use any object in a boolean context.
Sequence length. We have seen that we can call the len function to determine the length of a sequence.
The len function invokes the len method of its argument to determine its length. All built-in sequence types implement this method.
Python uses a sequence's length to determine its truth value, if it does not provide a bool method. Empty sequences are false, while non-empty sequences are true.
Callable objects. In Python, functions are first-class objects, so they can be passed around as data and have attributes like any other object. Python also allows us to define
the left operand, then checks for an radd method on the value of the right operand. If either is found, that method is invoked with the value of the other operand as its argument.