How to typecast a list as my own custom Matrix class?
<p>I have a <code>Matrix</code> class:</p>

<pre><code>class Matrix(object):
    def __init__(self,row,col):
        self.row=row
        self.col=col
        self.matlist=[]
        self.create()
    def create(self):
        for i in range(self.row):
            rowlist=[]
            for j in range(self.col):
                element=input("Enter Row: {} Col: {} :  ".format(i+1,j+1))
                rowlist.append(element)
            self.matlist.append(rowlist)   

    def __str__(self):
        j=str()
        for i in range(len(self.matlist)):
            for j in range(len(self.matlist[i])):
                j+=str(self.matlist[i][j])+"  "
            j+="\n"
        return j

    def __add__(self,y):
        newmatrix=[]
        el1=self.matlist
        el2=y.matlist

        if (len(el1)==len(el2)) and (len(el1[0])==len(el2[0])):
            for i in range(len(el1)):
                newlist=[]
                for j in range(len(el1[i])):
                    m=el1[i][j]+el2[i][j]
                    newlist.append(m)
                newmatrix.append(newlist)
            return newmatrix
</code></pre>

<p>and I have created two matrix objects:</p>

<pre><code>m=Matrix(2,2)
n=Matrix(2,2)
</code></pre>

<p>and then I add the Matrices:</p>

<pre><code>k=m+n
</code></pre>

<p>which calls the <code>__add__()</code> method which returns a <code>list</code>. But I want it to return it as a <code>Matrix</code> object so that when I try to print it, the <code>__str__()</code> method gets called and the <code>list</code> dosent simply get printed. Is there some way to typecast that <code>list</code> into <code>Matrix</code>?</p>

<p>Something like this should work.</p>

<p>First, a classmethod to create a matrix from a list:</p>

<pre><code>class Matrix(object):
    def __init__(self, row=None, col=None):
        self.matlist = []
        if row and col:
            self.row = row
            self.col = col
            self.create()

    @classmethod
    def fromlist(cls, list):
        res = Matrix()
        for row in list:
            res.matlist.append(row)
        return res
</code></pre>

<p>Then, the <code>__add__</code> method uses said method to return a <code>Matrix</code>:</p>

<pre><code>def __add__(self,y):
    newmatrix=[]
    el1=self.matlist
    el2=y.matlist

    if (len(el1)==len(el2)) and (len(el1[0])==len(el2[0])):
        for i in range(len(el1)):
            newlist=[]
            for j in range(len(el1[i])):
                m=el1[i][j]+el2[i][j]
                newlist.append(m)
            newmatrix.append(newlist)
        return Matrix.fromlist(newmatrix)
</code></pre>

<p>Note that there are some checks you should do. For example, this code doesn't check that all the rows are the same size. Other check you didn't consider in your code is that when adding two <code>Matrix</code> object, they both should be the same size.</p>

python python-2.7 matrix