Chapter 12 Classes
12.6 More Class ExamplesΒΆ
Classes can be used to organize data structures, making them easier to maintain. In the Account example, various sources of information about an account are aggregated to a single Account object, and managed by attributes and methods. Without a custom type definition by the class statement, it would be more difficult to write a program that manages such information.
Another example is matrix that can be defined as follows:
The class Matrix above implements some matrix operations, including get_row, get_column, scaling and addition. It provides a centralized organization of data, and is therefore easier to use compared with a set of global functions that directly handle lists of lists.
The matrix addition and scaling operations are implemented using the special methods __add__ and __mul__, respectively. In __mul__, type checking is performed to decide whether the second operand is an integer or not. The identifier int here represents the int type. If the second operand to __mul__ is an integer, scaling is performed; otherwise the method performs nothing and returns None.
© Copyright 2024 GS Ng.