类型错误: 类型对象'State'没有属性'S'



我正在研究以下模型,用于模拟python中的流行病(适合当前情况(。 这是我正在处理的代码:

import modsim
tc = 3 #time between contacts
tr = 4 #time between recoveries
cr = 1/tc #contact rate per day(beta)
rr = 1/tr #recovery rate per day(gamma)
S = 89
I = 1
R = 0
t0 = 0
t_end = 7*14
class State:
def __init__(self, S, I, R):
self.S = S
self.I = I
self.R = R
class System:
def __init__(self, init, t0, t_end, cr, rr):
self.init = init
self.t0 = t0
self.t_end = t_end
self.cr = cr
self.rr = rr

def update_func(state, t, system):
s = state.S
i = state.I
r = state.R
infected = system.cr * i * s
recovered = system.rr * i
s -= infected
i += infected - recovered
r += recovered
l1=[s,i,r]
x=0
for attr, value in state.__dict__.items():
setattr(state, attr, l1[x])
x+=1
return State
def run_sim(system, update_func):
state = system.init
for t in range(system.t0, system.t_end):
state = update_func(state, t, system)
return state
#driver code
state = State(89, 1, 0)
init = State(89, 1, 0)
sum = 0
for attr, value in init.__dict__.items():
sum += value
for attr, value in init.__dict__.items():
new_val = value/sum
setattr(init, attr, new_val)
system = System(init, t0, t_end, cr, rr)
final_state = run_sim(system, update_func)
print(final_state)

但是,每当我运行该程序时,我都会得到:

AttributeError: type object 'State' has no attribute 'S'

我不太确定我做错了什么。出现此问题的原因是 init 对象在作为 System 类对象的值提供时,会丢失其所有属性和属性,从而导致 update_func 函数中出现此错误。

问题是你从update_func返回State(没有属性S的类(而不是state(对象(。

问题出在这一行:

return State

这个循环执行了一次:

for t in range(system.t0, system.t_end):
state = update_func(state, t, system)

现在,update_func返回State(类(而不是state(对象(。因此,当循环进入第二次迭代时,您实际上是在传递State而不是state状态变量,因此它说:

AttributeError: type object 'State' has no attribute 'S'

最新更新