0

Please make me understand this code

Vector class related https://code.sololearn.com/cqtBs7vX7Xsh/?ref=app

19th May 2020, 11:10 PM
Shoe Finder
Shoe Finder - avatar
2 Respuestas
0
[Part 1] It's simply a class which represents a multidimensional vector. In this class, an internal list called _coords is used to keep track of the different vector components. Using magic methods (e.g. __add__, __eq__, __setitem__, etc.), the behaviour of the class is defined. As an example, consider the 'len' function. In this code, you want to be able to use the 'len' function with an instance of the class. However, as the class itself doesn't really have a length, python doesn't know what to do. By defining the magic method __len__, you basically tell python what to do. In this case, the __len__ magic method simply returns the length of the internal _coords list. Similarly, the __getitem__ magic method allows you to use the instance of the class as if it were a list (which it isn't). As you can see in the code, this magic method simply accesses the corresponding element in the _coords list. But this only works because you defined the __getitem__ magic method.
21st May 2020, 8:25 PM
DeX97
0
[Part 2] By defining all these magic methods, you can fully customise the behaviour of the class to your liking.
21st May 2020, 8:27 PM
DeX97