Having recently finished the Intermediate Python3 course, I decided to test myself with a couple of projects of my own. Coming from a purely mathematical background, I’ve decided on 2 separate projects towards that end. One is making a Matrix class with many operations of matrices in place, and the other will be for polynomials. To be clear, I’m sure there are modules out there with matrix and polynomial classes, but I’m trying to make something myself, using the skills I’ve learned.
Now to my question: is possible when defining a class which has a subclass to, during the initialization of an object from that class, test the input and, if a certain condition is met, instead create the object as being one from the subclass? Here’s a couple of examples of what I mean from my specific projects:
Example 1: My Matrix class will have a SquareMatrix subclass with added functionality of determinants and inverses. The way I have defined my Matrix class so far takes an input of a list of lists of
float which represent the rows of the matrix, and then uses that data to generate two dictionaries,
self.columns. During this process, am I able to test
if len(self.rows) == len(self.columns) (which would make the matrix square) and, if so, instead instantiate the object as a SquareMatrix object?
Example 2: I have not yet started on it, but my Polynomial class will have a Quadratric subclass, with the ability to find solutions and factor (maybe. still working through some details in my head how I would make that one work). The Polynomial class would accept a list of
float which represent the coefficients of the polynomial. During the initialization of a polynomial, test if the length of the input list is 3 (which would make the polynomial quadratic) and, if so, instead instantiate the object as a Quadratic object?
My instinct is that what I’m looking for cannot be done and instead the testing needs to be done in the program which is instantiating the objects. But I feel like it would be cleaner if class itself could handle the testing, so I figured I’d still ask