簡體   English   中英

"幫助 Python UnboundLocalError:賦值前引用的局部變量"

[英]Help with Python UnboundLocalError: local variable referenced before assignment

我以前發布過類似的問題,但是,我想我可能誤解了我的問題,所以我可以在這里發布我的原始代碼,並尋找可以幫助我的人,我現在真的被困住了..非常感謝。

from numpy import *
import math as M

#initial condition  All in SI unit
G=6.673*10**-11   #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10           #time step
#Creat arrays
vs=array([[0,0,0]])     #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])           
re=array([[0,1.4960*10**11,0]])

#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms 
ve=ve+fe*dt/me

n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
    rs,re=update_r(rs,re,n,dt)
    fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
    fe=-fs
    return fs,fe

#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
    fs,fe=force(n,ms,me,rs,re,G)
    i=arange(n)
    vs=vs+fs[:]*i[:,newaxis]*dt/ms
    ve=ve+fe[:]*i[:,newaxis]*dt/me
    return vs,ve

#update position
def update_r(rs,re,n,dt):
    vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
    i=arange(n)
    rs=rs+vs[:]*i[:,newaxis]*dt
    re=re+ve[:]*i[:,newaxis]*dt
    return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? – 

在這段代碼中你在哪里調用force?

無論如何,問題出在update_r中。 您在update_r的第一行中引用vs,即使此函數中未定義vs。 Python沒有關注上面定義的vs。 嘗試添加

global vs

作為update_r的第一行或將update添加到update_r的參數列表中

update_r的第一行,你有vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe) 查看您正在調用的函數。 您正在使用一堆參數調用update_v 其中一個參數是vs 但是,這是vs出現的第一次該功能。 變量vs還沒有與之關聯的值。 嘗試首先初始化它,你的錯誤應該消失

把一個附加的global包含每個畢竟您的全局聲明def聲明。 否則,所有全局變量都會轉換為def中的本地變量而不是它。

def update_v(n,vs,ve,ms,me,dt,fs,fe):
    global vs, ve, ...  

在第39行你做

vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)

而你在一個功能。 由於您定義了一個名為vs全局變量,因此您可以期望這樣做。 如果你有:

vs_new,ve_new = update_v(n,vs,ve,ms,me,dt,fs,fe)

因為那時解釋器在函數參數中知道vs是全局參數。 但是由於你在左側有vs ,你創建了一個未初始化的局部變量。

但是老兄, 你的代碼中有一個更大的問題 :update_r調用update_v,update_v調用force,強制調用update_r - 你會得到堆棧溢出 :)

當我的類名被分配給一個與其名稱完全相同的變量時,我得到了這個錯誤。 例如ClassName = ClassName.<\/code> 如果您來自 .Net,您可以這樣做

"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM