i try to write a template class in python. my aim is importing this class for other projects.
class have a class attribute M. it's default value is zero. when i import class in other project i change M with a new value. after that, i sampling class but instance attributes dont change. they consider zero value for M. how can i solve this problem? i dont want to use instance attribute for 'M'.
import numpy as np
class Example():
M=0
matrix=np.ones((M,M))
def __init__(self,a,b):
self.a=a
self.b=b
self.operate()
def operate(self):
Example.matrix=Example.matrix*self.a*self.b
print(Example.matrix)
Example.M=5
m1=Example(3,5)
when i run the code,
[] is the result.
but i expect this matrix:
[[15. 15. 15. 15. 15.] [15. 15. 15. 15. 15.] [15. 15. 15. 15. 15.] [15. 15. 15. 15. 15.] [15. 15. 15. 15. 15.]]
This is because
matrixis decrlared once, if you try to modifyM, it doesn't change thematrix.By changing the code a bit, this gives:
Basically, I moved
Mandmatrixto__init__, changedMtoself.Mandmatrixtoself.matrix.