import numpy as np
>>> class prof:
... def __init__(self,q,Q):
... self.q,self.Q = q,Q
... def profitmatrix(self):
... q,Q= self.q,self.Q,
... pimat=np.empty([1, Q+1])
... list1=[]
... for z in range(Q+1):
... list1.append(z/(2**(z+1)))
... sum1=sum(list1)+(Q/(2**(Q+1)))
... for i in range(Q+1):
... if i<=q:
... pimat[:,i]=sum1
... else:
... pimat[:,i]=0
... return pimat
...
>>> y= prof(1,2)
>>> print y.profitmatrix()
[[ 0.25 0.25 0. ]]
>>> sum1
0.75
我想为pimat赋值sum1。但是,尽管记住sum1的值,但一旦程序继续进入循环,它就会被改变。我不知道为什么会发生这种情况* 强文 *
答案 0 :(得分:0)
问题是你在循环中覆盖了sum1的值。这可能是答案,但目前还不清楚你想要做什么:
import numpy as np
class prof:
def __init__(self,q,Q, sum1):
self.q,self.Q = q,Q
def profitmatrix(self):
q,Q= self.q,self.Q,
pimat=np.empty([1, Q+1])
list1=[]
for z in range(Q+1):
list1.append(z/(2**(z+1)))
suma=sum(list1)+(Q/(2**(Q+1)))
for i in range(Q+1):
if i<=q:
pimat[:,i]=sum1
else:
pimat[:,i]=0
return pimat
sum1 = 0.75
y= prof(1,2, sum1)
print y.profitmatrix()
@ user2357112是正确的,无论你想做什么,该类范围内的sum1变量与你在脚本末尾访问的变量不同。