Overloading the [ ] operator for indexing and slicing
The square bracket operator [ ] is used by built-in collection data types such as lists, tuples and dictionaries. The item placed inside the brackets can be a single object…
The square bracket operator [ ] is used by built-in collection data types such as lists, tuples and dictionaries. The item placed inside the brackets can be a single object…
When we discussed encapsulation in classes, we saw that a class's data fields should be kept as private fields, with getter and setter methods being provided to access or change…
The most common use of a class is as a recipe for creating objects, each of which is a specific instance of the class. The methods that we've defined inside…
We introduced generator functions as a way of writing functions that yield successive values while maintaining the function's state in memory. We've seen how to use the yield statement to…
[latexpage] A normal function in Python can be terminated with a return statement, which may or may not return a value back to the statement that called the function. After…
[latexpage] A recursive function is one that calls itself. We can illustrate this with the usual example: the factorial function. Before presenting the example, however, it's advisable to begin with…
Input errors One of the most tedious jobs in writing code designed to be used by others is checking a user's input to make sure it's valid. As an example,…
We've seen how to write and read text files. This is fine if you want to store the data in a human readable form or transfer the data to some…
Writing and reading text files in Python is fairly straightforward. It's easiest to illustrate the process with an example. Here is some code that generates the 52 cards in a…
[latexpage] Overloading the six comparison operators works in a similar way to the overloading of arithmetic operators. The operators and their associated methods are: Default behaviour Before we try overloading…