2012-07-25 3 views
0

SimPy 모듈과 함께 Python2.7을 처음 사용하고 있습니다. 나는이 두 가지를 모두 배우기 때문에 이것을 정확하게 설명하기를 바랍니다. 내 프로그램의 목표 : 수요 개체를 생성하고 매주 숫자를 생성하십시오. 목록에 저장하십시오. Demand 개체에서 만든 번호를 기반으로 Supply 개체를 만들고 매주 한 번씩 번호를 생성합니다. 52 번호를 만들고 목록에 추가 할 수있는 것처럼 보이지만 Supply 개체를 통해 목록을 읽을 수는 없습니다. 다음과 같이 내 코드는 : 내 프로그램을 실행하면, 내 수요를 생성하고 콘솔에 주간 및 누적 값을 출력Python 2.7 : 목록 액세스 기능

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의 목록을 인쇄 .

누구든지 공급 업체 개체 및 기능에서 목록을 성공적으로 읽으려면 올바른 경로로 안내 할 수 있습니까? 감사합니다. 파이썬에 대한 내 명확한 '새로운'전망을 변명하십시오.)

+0

supply_rate() 및 weeklyDemand() 메소드의 들여 쓰기가 엉망입니다. –

답변

0

D1ValsS1Vals은 모듈 범위에서 정의됩니다. 문제없이이 모듈에 x=S1Vals[-7:]과 같은 표현식을 쓸 수 있어야합니다.

이 이러한 변수의 값을 값을 액세스하고 돌연변이 작동

,

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

작동합니다 너무.

그러나 그들에게 할당하려면, 당신은 global S1Vals 라인이 생략되면

def erase_supply(): 
    '''Clear the list of supply values''' 
    global S1Vals 
    S1Vals = [] 

글로벌

로 선언 할 필요, 결과는 함수 로컬 변수 S1Vals가 할당 문에 의해 정의되는 것 동일한 이름의 모듈 수준 변수를 섀도 잉하십시오.

글로벌 문을 사용하지 않으려면 실제 모듈 이름 을 사용하여 이러한 변수를 참조하십시오. 귀하의 코드가 SupplyAndDemandModel.py에 정의되어 있다고 가정하겠습니다.

이 파일의 상단에

당신은

import SupplyAndDemandModel 

를 넣을 수 있습니다 다음 모듈 이름을 사용하여 해당 모듈 범위의 변수를 참조 : 이것은 명확하게 당신을 나타내는하는 방법을 제공합니다

SupplyAndDemandModel.S1Vals = [] 

을 모듈 수준 변수에 액세스/수정 중입니다.

+0

@Colin : 감사합니다. 실제 프로그램에서 확인되었습니다. – manengstudent

+0

@Dave 시간을 내 주셔서 감사합니다. 학습 곡선이이 단계에서 조금 복잡해 보입니다. 나는 '초보자'코딩의 수정본을 찾기를 희망했다. 또 다른 사실은 내가 수동으로 D1Vals에 임의의 숫자를 채우면 프로그램이 작동한다는 것입니다 (심지어 len (D1Vals)가 51 대신 52). 노력을 계속하고, 여전히 어떤 도움을 주셔서 감사합니다 – manengstudent

+0

@ Dave.귀하의 충고에 따라 목록을 전역으로 선언하여 결과를 얻을 수 있었고 목록에 액세스 할 때마다 항목을 삭제했습니다. 그래서 내가 변수를 액세스 할 수있는 곳을 이해하게 만들었 기 때문에 가치있는 학습 활동이었습니다. 감사. 내가 작업 코드를 게시 할 의도가 있는지 알 수 없습니까? – manengstudent