【问题标题】:Python - different variable with each function runPython - 每个函数运行的不同变量
【发布时间】:2026-01-12 19:45:02
【问题描述】:

我会尽力解释这一点。我创建了一个函数,它使用 Tkinter 的 tkFileDialog.askopenfilename() 让您选择一张照片。脚本返回两个变量中的坐标:

def getCoordinates():

    # code to get coordinates here

    # variables for lat and long
    global latitude
    global longitude

    latitude
    longitude

现在,我创建了一个函数,它两次调用第一个函数 getCoordinates()。所以这要求选择两张照片。

def TwoPic():
    run = 0
    while run < 2:
        run = run + 1
        getCoordinates()

        FirstRunLat = latitude
        FirstRunLong = longitude
        print FirstRunLat + " " + FirstRunLong

        SecRunLat = latitude
        SecRunLong = longitude
        print SecRunLat + " " + SecRunLong

        ThirdRunLat = latitude
        ThirdRunLong = longitude
        print ThirdRunLat + " " + ThirdRunLong

    root.quit()

基本上会发生什么,SecRunLat & SecRunLong 和 ThirdRunLat & ThirdRunLong 最终将与 FirstRunLat 和 FirstRunLong 相同。

所以我要问的是,我如何运行该函数来获取坐标并为变量赋予不同的名称,这些名称保持唯一并且在我再次运行该函数时不会重复?

希望这是有道理的。

非常感谢您。

【问题讨论】:

  • 这是一个非常糟糕的方法。要么使用列表或字典来存储FirstRunLat 和其余部分,要么只在没有循环的情况下进行函数调用。

标签: python function variables unique


【解决方案1】:

你从你的函数中返回值,并将它们分配为一个元组:

def getCoordinates():
    # code to get coordinates here

    return latitude, longitude

当调用这些时:

def TwoPic():
    run = 0
    while run < 2:
        run = run + 1

        FirstRunLat, FirstRunLong = getCoordinates()

        print FirstRunLat + " " + FirstRunLong

        SecRunLat, SecRunLong = getCoordinates()
        print SecRunLat + " " + SecRunLong

        ThirdRunLat, ThirdRunLong = getCoordinates()
        print ThirdRunLat + " " + ThirdRunLong

    root.quit()

不要使用全局变量来传递函数结果;这就是return 语句的用途。

【讨论】:

    【解决方案2】:

    好吧,如果你想继续使用全局变量,我只会使用列表:

    def TwoPic():
        run = 0
        Lats = []
        Longs = []
        while run < 2:
            run = run + 1
            getCoordinates()
    
            Lats.append(latitude)
            Longs.append(longitude)
    
        root.quit()
    

    【讨论】:

      【解决方案3】:

      基本上会发生什么,SecRunLat & SecRunLongThirdRunLat & ThirdRunLong 最终将与 FirstRunLatFirstRunLong 相同。

      当然 - 您不会更改中间值,因为您只调用一次 getCoordinates()

      返回结果会更好:

      def getCoordinates():
      
          # code to get coordinates here
      
          return latitude, longitude # as a tuple.
      
      def TwoPic():
          run = 0
          results = []
          while run < 2:
              run = run + 1
      
              lat, lng = getCoordinates()
              print lat + " " + lng
              results.append((lat, lng))
          print results
      
          root.quit()
      

      【讨论】:

        最近更新 更多