# Revision history [back]

I do not think it is easy without modifying Sage source code.

One problem is that most matrix classes are so called "extension class" with read-only attributes

sage: m = matrix()
sage: m.new_attr = 3
Traceback (most recent call last):
...
AttributeError: 'sage.matrix.matrix_integer_dense.Matrix_integer_dense' object has no attribute 'new_attr'


To be compared with

sage: p = Permutation([3,2,1])
sage: p.new_attr = 3
sage: print p.new_attr
3


You would have been able to do it on permutations via

sage: p = Permutation([3,2,1])
sage: p.__class__.new_method = lambda s: 1
sage: p.new_method()  # it works!
1
sage: q = Permutation([4,3,2,1])
sage: q.new_method()  # it also works!
1


But this approach would also fail for matrices since there are many classes of matrices.

[EDIT] First of all there is a stupid reason for that. The method call is implemented as a componentwise call as in

sage: m = matrix(2, [cos(x), sin(x), -sin(x), cos(x)])
sage: m(pi/4)
<A TON OF WARNINGS>
[ 1/2*sqrt(2)  1/2*sqrt(2)]
[-1/2*sqrt(2)  1/2*sqrt(2)]


The above behavior is incompatible with having m(v) returning m*v for vectors v (because you might have functions that accept vectors as input). Whether the current behavior is desirable I do not know.

[ORIGINAL ANSWER] Then, I do not think it is easy without modifying Sage source code.

One problem is that most matrix classes are so called "extension class" with read-only attributes

sage: m = matrix()
sage: m.new_attr = 3
Traceback (most recent call last):
...
AttributeError: 'sage.matrix.matrix_integer_dense.Matrix_integer_dense' object has no attribute 'new_attr'


To be compared with

sage: p = Permutation([3,2,1])
sage: p.new_attr = 3
sage: print p.new_attr
3


You would have been able to do it on permutations via

sage: p = Permutation([3,2,1])
sage: p.__class__.new_method = lambda s: 1
sage: p.new_method()  # it works!
1
sage: q = Permutation([4,3,2,1])
sage: q.new_method()  # it also works!
1


But this approach would also fail for matrices since there are many classes of matrices.