【问题标题】:Python - Using list outside functionPython - 在函数外使用列表
【发布时间】:2014-01-28 11:36:31
【问题描述】:

继续我之前的问题:Python - different variable with each function run

我现在可以多次运行该函数并附加到一个很棒的列表中。现在的问题是访问函数之外的列表。

def TwoPic():
    run = 0
    Lats = []
    Longs = []
    while run < 2:
        run = run + 1
        print ("Start func TwoPic")
        oneMorePic()
        Lats.append(finalLatSecondPhoto)
        Longs.append(finalLongSecondPhoto)

        print '\n\nYour coordinates: ' + rippedLatitudeTwo + ',-' + rippedLongitudeTwo
        print "Below are the 2 new lats and longs in a list"
        print Lats
        print Longs
        root.quit()
    return Lats, Longs

root = Tk() 

label = Label(root, text="Choose Iterations", font=('Calibri', 12))
button1 = Button(root, text = "0 Pics", command = Quit)
button2 = Button(root, text = "1 Pic", command = OnePic)
button3 = Button(root, text = "2 Pics", command = TwoPic)

label.pack()
button1.pack()
button2.pack()
button3.pack()
root.mainloop() 

print "List: "

print Lats, Longs # Should print my list....I'm now outside of the function

错误:

Your coordinates: 43 48.54,-1 24.58
Below are the 2 new lats and longs in a list
[43.809, 43.809]
[1.409, 1.409]
List:
Traceback (most recent call last):
  File "simonsScript.py", line 447, in <module>
    print Lats, Longs
NameError: name 'Lats' is not defined

为什么不让我在函数之外打印列表?

【问题讨论】:

  • LatsLongsTwoPic() 范围内定义它们不是全局的,您正在尝试访问未定义的变量。
  • print之前你需要打电话给Lats, Longs = TwoPic()
  • "I can now run the function multiple times and append to a list which is great" 请记住,在不同的函数调用中,您正在重新定义 LatsLongs 列出内部函数。

标签: python list function tuples


【解决方案1】:

当您尝试打印时,您的 Lats 变量不在范围内。 尝试在函数之外定义它(注意:拥有“全局”变量很少是一个好主意;我假设您知道自己在做什么,并且您没有其他明智的选择)。

Lats = []

def TwoPic():
    run = 0
    [...]

print Lats

另外,用大写字母定义变量也不是一个好习惯。当然,这取决于您的命名约定,但是如果您习惯了常见的做法,将来可能会更容易阅读其他人的代码。

这意味着:

lats = []
def two_pic():
    run = 0
    [...]

print lats,long..

如果您想了解更多关于 Python 良好编码实践(不一定与命名变量相关)的信息,请搜索“pep8”或查看此link

【讨论】:

  • 谢谢,我知道我现在做错了什么。我通常使用camelCase。对于这个例子,我更专注于让代码工作而不是案例。我现在就回去解决这一切。再次感谢。
  • 实际上这个解决方案并不是一个好的解决方案,尽量避免使用全局范围变量!如果你真的需要,那就创建一个类!
  • @zmo 你是对的,这是一个糟糕的解决方案,但由于涉及到按钮和标签,我认为还有其他限制。我会编辑答案。
【解决方案2】:

为什么不让我在函数之外打印列表?

因为它是仅存在于函数中的本地名称(并且您的 LatsLongs 列表仅在函数执行期间存在。

【讨论】:

    【解决方案3】:

    在 TwoPic() 范围内定义的 Lats 和 Longs 不是全局的,您正在尝试访问未定义的变量。

    更改您的代码以首先通过您创建的函数定义它们,然后打印它们的值。

    Lats, Longs = TwoPic() 
    print "Lists:", Lats, Longs
    

    【讨论】:

    • 实际上我认为它们应该只在按下按钮后立即定义。整个打印应该是TwoPic() 函数的一部分。
    • @hochl 我接受这个建议,只是为了尽可能简单地展示问题。
    【解决方案4】:

    您尝试在尝试打印它们的地方访问超出范围的变量。在您的代码中,您只能访问函数内的这些变量。您的问题有 3 个解决方案。

    1:让它们像 gloabl 一样:

    def TwoPic():
        run = 0
        global Lats = []
        global Longs = []
        [...]
    

    2:定义函数外的变量

    Lats = []
    Longs = []
    def TwoPic():
        run = 0 
        [...]
    

    3:从函数中返回它们

    【讨论】:

      【解决方案5】:

      你的所作所为很荒谬……

      您创建一个按钮,例如当您单击它时,您会进入TwoPic()

      button3 = Button(root, text = "2 Pics", command = TwoPic)
      

      虽然您想在定义 LatsLongs 之前获取数据。

      一旦定义了LatsLongs,就应该在TwoPic 中使用它们。例如,在 Label 中显示它们,或者像您已经在 print 语句中所做的那样。

      另一种解决方案:

      class HandleLongLats:
          def __init__(self):
              self.longs = []
              self.lats = []
      
          def twoPic(self):
              run = 0
              while run < 2:
                  run = run + 1
                  print ("Start func TwoPic")
                  oneMorePic()
                  self.lats.append(finalLatSecondPhoto)
                  self.longs.append(finalLongSecondPhoto)
      
                  print '\n\nYour coordinates: ' + rippedLatitudeTwo + ',-' + rippedLongitudeTwo
                  print "Below are the 2 new lats and longs in a list"
                  print self.lats
                  print self.longs
                  root.quit()
              self.showList()
      
          def showUI(self):
              root = Tk() 
      
              label = Label(root, text="Choose Iterations", font=('Calibri', 12))
              button1 = Button(root, text = "0 Pics", command = Quit)
              button2 = Button(root, text = "1 Pic", command = onePic)
              button3 = Button(root, text = "2 Pics", command = self.twoPic)
      
              label.pack()
              button1.pack()
              button2.pack()
              button3.pack()
              root.mainloop() 
      
          def showList(self):  
              print "List: "
              print self.lats, self.longs # Should print my list....I'm now outside of the function
      

      这里的想法是让latslongs 成为一个类的成员,这样您就可以在另一个函数中使用它们。

      【讨论】:

      • 感谢 Zmo。我试过你的代码,我有点困惑。 GUI 没有按预期自行弹出,所以我尝试了: showUI() 但它没有启动它。我如何真正开始上课?
      • @zmo :请确保您发布的代码没有明显错误。就像,instancemethods 期望 self 作为第一个参数... :-/
      猜你喜欢
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 2020-12-26
      • 2011-06-26
      相关资源
      最近更新 更多