2011-12-13 7 views
1

나는 하나 이상의 다른 함수 내에서 (비 로컬 변수를 사용하여) 파이썬 3 함수를 사용하는 방법을 다시금 정의하지 않고서 알아 내려고하고있다.파이썬에서 내부 함수의 재사용

def inner(airplane): 
    nonlocal var 
    if airplane == "Alpha": 
     var = a 
    elif airplane == "Beta": 
     var = b 
def outer1(airplane): 
    inner(airplane) 
    do stuff with var 
def outer2(airplane) 
    inner(airplane) 
    do other stuff with var 

outer1("FirstAirplane") 
outer2("SecondAirplane") 

나는 오류 (SyntaxError: No binding for nonlocal 'var' found)를 받고 있어요하지만 난 매우 잘못이 일을하고있어 의심 : 여기가 무슨 뜻인지 매우 간단한 예입니다. 나는 inner()을 단독으로 운영 할 생각이 없습니다. inner()을 올바르게 재사용하려면 어떻게해야합니까? 난 그냥 outer1() 안에 정의 할 수없고 outer2()에서 다시 사용할 수 있습니까?

좋아, 어 ... 인기 수요에 ... 여기 내 코드의 관련 섹션은 ...

def planeandoffset(airplane): 
    if airplane == "Zulu": 
     linename = "\\[\\INOV" 
     charoffset = 14 
    elif airplane == "Lima": 
     linename = "\\[\\ILIM" 
     charoffset = 10 
    elif airplane == "Mike": 
     linename = "\\[\\IMIK" 
     charoffset = 10 
    else: 
     print("There is no airplane by that name.") 
    latstart = charoffset 
    latend = 7 + charoffset 
    lonstart = 9 + charoffset 
    lonend = 17 + charoffset 
    return airplane, linename, latstart, latend, lonstart, lonend 

def latlongen(workingline, latstart, latend, lonstart, lonend): 
# Determine Latitude and Longitude in decimal format 
    latraw = workingline[latstart:latend] 
    if latraw[0:1] == "S": 
     pm = "-" 
    else: 
     pm = "" 
    hours = float(latraw[3:5] + "." + latraw[5:]) 
    decimal = hours/60 
    latitude = float(latraw[1:3]) + decimal 
    latitude = float(pm + str(latitude)) 
    lonraw = workingline[lonstart:lonend] 
    if lonraw[0:1] == "W": 
     pm = "-" 
    else: 
     pm = "" 
    hours = float(lonraw[4:6] + "." + lonraw[6:]) 
    decimal = hours/60 
    longitude = float(lonraw[1:4]) + decimal 
    longitude = float(pm + str(longitude)) 
    return latitude, longitude 
def kmlplanegen(airplane): 
    planeandoffset(airplane) 
    global afffilename, iconurl, kmlwrite 
    affread = open(afffilename) 
    while True: 
     line = affread.readline() 
     # Choose appropriate line 
     if line.startswith(linename): 
      workingline = line 
     elif len(line) == 0: # Zero length indicates EOF (Always) 
      break 
     else: 
      pass 
    try: 
     latlongen(workingline, latstart, latend, lonstart, lonend) 
    # Generate kml for Airplane 
     print(''' <Placemark> 
      <Style> 
       <IconStyle> 
        <Icon> 
         <href>{0}</href> 
        </Icon> 
       </IconStyle> 
      </Style> 
      <name>{1}</name> 
      <description>Latitude: {2} Longitude: {3}</description> 
      <Point> 
       <coordinates>{3},{2},0</coordinates> 
      </Point> 
     </Placemark>'''.format(iconurl,airplane,latitude,longitude), file=kmlwrite) 
    except Exception: 
     exit(1, "There was an error. This message is kind of worthless. Stopping Program") 

def kmlpathgen(airplane): 
    planeandoffset(airplane) 
    global afffilename, kmlwrite 
    # Generate kml for Airplane Path 
    print(''' <Style id="yellowLineGreenPoly"> 
     <LineStyle> 
      <color>7f00ffff</color> 
      <width>4</width> 
     </LineStyle> 
     <PolyStyle> 
      <color>7f00ff00</color> 
     </PolyStyle> 
    </Style> 
    <Placemark> 
     <name>{0} Path</name> 
     <description>Transparent green wall with yellow outlines</description> 
     <styleUrl>#yellowLineGreenPoly</styleUrl> 
     <LineString> 
      <extrude>1</extrude> 
      <tessellate>1</tessellate> 
      <altitudeMode>relativeToGround</altitudeMode> 
      <coordinates>'''.format(airplane), file=kmlwrite) 
    try: 
     affread = open(afffilename) 
     while True: 
      line = affread.readline() 
      if len(line) == 0: # Zero length indicates EOF (Always) 
       break 
      elif line.startswith(linename): 
       workingline = line 
       latlongen(workingline, latstart, latend, lonstart, lonend) 
       print("     {0},{1},0".format(longitude,latitude), file=kmlwrite) 
      else: 
       pass 
    except NameError: 
     pass 
    finally: 
     print('''   </coordinates> 
      </LineString> 
     </Placemark>''', file=kmlwrite) 
+0

클래스가 필요합니다. http://docs.python.org/tutorial/classes.html – Crisfole

+0

[ '로컬이 아닌 것'에 대한 설명] (http://stackoverflow.com/a/) 1261961/832391). –

+1

간단히 대답하면 역동적 범위 지정을 요구하고 있지만 파이썬 ('로컬이 아닌 경우와없는')은 렉시 컬 범위 지정 만 제공합니다. – delnan

답변

3

그냥 프로그램을 배우고 있습니까?

비 로컬 항목은 잊어 버리십시오.

var = inner(airplane) 

편집 :

것은 단순히 호출 :

planeandoffset(airplane) 
이 작업을 수행하는 올바른 방법은 return varvar을 반환 한 후 호출하는 상황에서 그 결과를 할당하는 것입니다

반환 된 값을 가지고 아무것도 수행하지 않습니다. 이들에 액세스하려면 다음을 수행하십시오.

airplane, linename, latstart, latend, lonstart, lonend = planeandoffset(airplane) 

나는 당신이 그 세계에서 무엇을하고 있는지 분석하지 않을 것입니다. 함수 사이에 매개 변수로 전달하거나 함수와 함께 클래스에 넣고 클래스 멤버로 액세스하십시오.

어느 쪽이든, 전역을 사용하지 않는보다 일반적인 프로그래밍 스타일을 배우기 위해 튜토리얼을 따르는 것이 좋습니다.

+1

불행히도 아니요, 저는 배우기 만은 아니지만 잘 다시 배우려고합니다. . 나는 매우 기능적이고, 아주 추악한 코드를 작성했다. 유지하는 것이 악몽 같아요. 코드를 작성하는 법을 배워야 할 필요가 있다고 생각했습니다. 가능한 한 가장 빨리 자갈을 긋는 방식으로 코드를 작성하는 것입니다. – Russianspi

+0

+1. 글로벌 및 비 로컬에 대해 잊어 버리십시오. 리턴을 사용하십시오. 간단하게. –

+0

네, 그 말이 맞는 것 같습니다. 내 변수를 "var"로 참조하거나 "inner.var"와 같은 것이 필요합니까? 아직도 제대로 작동하지 않습니다. "Outer"는 전역 변수 var를 찾고 있으며 찾을 수 없다고 말합니다. – Russianspi

관련 문제