Python2.7:访问lis的函数

2024-09-24 10:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python2.7和SimPy模块,第一次在这里发布。 我只是在学习这两种方法,所以我希望我能正确地解释这一点。 我计划的目的是: 创建一个需求对象并每周生成一个数字。 把它存储在一个列表中。 创建一个Supply对象并根据demand对象创建的数字每周生成一个数字。 我似乎能够创建我的52个数字,并将它们附加到一个列表中,但我无法成功地让Supply对象读取列表。 我的代码如下:

from SimPy.Simulation import *
import pylab as pyl
from random import Random
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# Model components
runLength = 51

## Lists for examination
D1Vals = []
S1Vals = []

.... other code lines

class Demander(Process):

# This object creates the demand, and stores the values in the 'D1Vals' list above

def weeklyDemand(self):  # Demand Weekly
    while True:
            lead = 1.0      # time between demand requests
            demand = random.triangular(20,110,370)  # amount demanded each increment
            #yield put, self, orderBook, delivery
            print('Week'+'%6.0f: Need %6.0f units: Total Demand = %6.0f' %
                    (now(), demand, orderBook.amount))
            yield hold, self, lead
            yield put, self, orderBook, demand
            D1Vals.append(demand)

# This object is trying to read each value iteratively in D1Vals, 
  and create a supply value and store in a list 'S1Vals'

class Supplier(Process):

def supply_rate(self):
    lead = 1.0
    for x in D1Vals:
            supply = random.triangular(x - 30, x , x + 30)               
            yield put, self, stocked, supply
            print('Week'+'%6.0f: Gave %6.0f units: Inv. Created = %6.0f' %
                    (now(), supply,stocked.amount))
            yield hold, self, lead
            S1Vals.append(stocked.amount)

..... other misc coding .....

# Model
demand_1 = Demander()
activate(demand_1, demand_1.weeklyDemand())
supply_1 = Supplier()
activate(supply_1, supply_1.supply_rate())
simulate(until=runLength)

当我运行我的程序时,它会创建我的需求并将每周值和累计值输出到控制台,它还会打印D1Vals列表,以确保它不是空的。在

有谁能指导我从供应商对象和函数成功读取列表的正确路径吗。 谢谢,请原谅我对python明显的“新鲜”看法;)


Tags: 对象inimportself列表as数字random
1条回答
网友
1楼 · 发布于 2024-09-24 10:26:10

D1Vals和{}在模块范围内定义; 你应该能写出像 x=S1Vals[-7:]该模块中的任何位置都没有问题。在

这用于访问这些变量的值并对其值进行变异, 所以

def append_supply( s ):
    S1Vals.append(s)

应该行得通。在

但是,要分配给它们,需要将它们声明为全局的

^{pr2}$

如果省略global S1Vals行,结果将是函数local 变量S1Vals由赋值语句定义,隐藏模块级别 具有相同名称的变量。在

避免使用global语句的一种方法是使用实际的模块名 引用这些变量。我假设您的代码是在中定义的 SupplyAndDemandModel.py。在

在这个文件的顶部你可以

import SupplyAndDemandModel

然后使用模块名称引用这些模块范围内的变量:

SupplyAndDemandModel.S1Vals = []

这提供了一种明确指示您正在访问/修改模块级变量的方法。在

相关问题 更多 >