Python 3.6: Using object instance name for raising errors

python python-3.x error-handling typeerror custom-errors

37 观看


18 作者的声誉

I'm attempting to create a 3-d graphics engine using Python 3.6, Tkinter, and specifically NOT pygame (or any other 3d graphics engines) as part of a university assignment.

Within this project, I have had to create a "matrix" class, which allows me to easily create and manipulate mxn matrices. I believe this to be crucial for transforming vectors in order to display items on a 2d display.

One method I would like my Matrix class to contain is matrix multiplication. I figured the first (and most important) thing to check when performing this method is to ensure that the width of the first matrix is equal to the height of the second matrix, as that is necessary for multiplying two matrices together.

If the two matrices cannot be multiplied together, I raise an TypeError, in which I want to say

"Matrix multiplication not possible. Width of {first matrix's name}: ({value}) is not equal to height of {second matrix's name}: ({value})".


apple = Matrix(2, 3, List_of_values)
#creates a matrix instance that is 2x3 and contains 6 values from a list

pear = Matrix(4, 3, Another_list_of_values)
#creates a matrix that is 4x3 and contains 12 values from another list


This should, when all is working, attempt to perform {apple x pear} mathematical operation, specifically with apple first and pear second

In this case, multiplication is obviously not possible: apple is 2 high and 3 wide, and pear is 5 high and 3 wide. I would like to raise an error like:

TypeError: Matrix multiplication not possible: Width of apple (3) is not equal to height of pear (4)

Instead, I get this:

TypeError: Matrix multiplication not possible: Width of <__main__.Matrix object at 0x1056117b8> (3) is not equal to height of <__main__.Matrix object at 0x105618e80> (4)

I believe I need to define the __name__ attribute within my matrix class, such that when apple.__name__ is called, it returns a string that contains the name "apple". Is this possible? Is this even a good idea? Is there a better coding practise I should follow instead?


作者: William Pulford 的来源 发布者: 2017 年 12 月 27 日

回应 1


18 作者的声誉


I wanted to mark this question as answered: jonrsharpe's answer in the comments explained it well, and Bryan Oakley added some helpful extra information. Thanks to you both.

作者: William Pulford 发布者: 2017 年 12 月 29 日