Python static variable in function global name not defined -
i have written function calculate heading between 2 points if vehicle reports it's moving , vehicle has moved 20cm between points.
the function uses static variables - or @ least if worked - keep track of previous positions , heading values.
here code:
def withcan(pos): eastdist = pos[0]-previous_pos[0] northdist = pos[1]-previous_pos[1] canflag = pos[2] if (canflag == 1 or canflag==2): if (previous_canflag == 1 , canflag == 2): previous_heading += 180.0 previous_canflag = canflag elif (previous_canflag == 2 , canflag == 1): previous_heading += 180.0 previous_canflag = canflag else: previous_canflag = canflag if ( (canflag == 1 or canflag == 2) , math.sqrt(northdist*northdist+eastdist*eastdist) > canstep ): previous_heading = math.degrees(math.atan2(eastdist, northdist)) previous_pos[0] = pos[0] previous_pos[1] = pos[1] return previous_heading withcan.previous_pos = [0.0,0.0] withcan.previous_heading = 0.0 withcan.previous_canflag = 0 withcan.canstep = 0.2 positions = backandforth([100,100]) #populates array of form [x,y,canflag] p in positions: print withcan(p)
i getting error says eastdist = pos[0]-previous_pos[0] nameerror: global name 'previous_pos' not defined
. please explain cause of error?
when this:
def foo(): pass foo.name = 1
you not creating global name name
. instead adding property foo
function! can access with:
def foo(): return foo.name foo.name = 1
but quite weird. if need global name, it:
def foo(): global name name += 1 return name name = 1
remember if want modify global name function, have declare global
. if fail this, can use cannot assign it.
your confusion static names may come using classes. note in code withcan
not class, plain function!
Comments
Post a Comment