Reputation: 43
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.]]
Upvotes: 2
Views: 82
Reputation: 5992
You need to move the definition of your matrix
inside the __init__
function - right now, the class is parsed, M
is set to 0
and matrix
is set to np.ones(0,0)
which is an empty list []
. Then, you assign 5
to M
, but matrix
remains unchanged.
So you need to either redefine matrix
manually:
Example.M = 5
Example.matrix = np.ones(Example.M, Example.M)
or you define a class method and use that set M
:
class Example():
M=0
matrix=np.ones((M,M))
@classmethod
def setM(m):
Example.M = m
or you move the definition of matrix
inside the __init__
method.
Upvotes: 2
Reputation: 99
This is because matrix
is decrlared once, if you try to modify M
, it doesn't change the matrix
.
By changing the code a bit, this gives:
import numpy as np
class Example():
def __init__(self,a,b):
self.M=5
self.matrix=np.ones((self.M,self.M))
self.a=a
self.b=b
self.operate()
def operate(self):
self.matrix=self.matrix*self.a*self.b
print(self.matrix)
Example.M=5
m1=Example(3,5)
Basically, I moved M
and matrix
to __init__
, changed M
to self.M
and matrix
to self.matrix
.
Upvotes: 0