【问题标题】:get rid of global variable in python3摆脱python3中的全局变量
【发布时间】:2013-03-30 04:14:31
【问题描述】:

首先,我分别在 windows 和 Linux 上使用 python 3.3 和 3.2。

我开始构建一个 rpn 计算器。看起来跨平台的关键监听器是 python 的一种圣杯。到目前为止,这似乎可以解决问题,但我还产生了其他问题:

  1. 我无法摆脱条目的全局变量并使用我的 堆。
  2. 看来我必须从内部构建程序 callback()

这是一个粗略的骨架,显示了我的方向。我是否错过了将信息传入和传出callback()的方法

目标是在我发现自己陷入callback() 之前构建一个 RPN 类。

import tkinter as tk

entry = ""
stack = list()

operators = {"+",
            "-",
            "*",
            "/",
            "^",
            "sin",
            "cos",
            "tan"}

def operate(_op):
    if _op == "+":
        print("plus")

def callback(event):
    global entry, stack
    entry = entry + event.char
    if event.keysym == 'Escape': # exit program
        root.destroy()
    elif event.keysym=='Return': # push string onto stack  TODO
        print(entry)
        entry = ""
    elif entry in operators:
        operate(entry)


root = tk.Tk()
root.withdraw()
root.bind('<Key>', callback)
root.mainloop()

【问题讨论】:

    标签: python-3.x tkinter global-variables


    【解决方案1】:

    您有多种选择来做您想做的事。

    1。为您的应用程序使用一个类

    在不使用全局变量的情况下做你想做的事的规范方法是将应用程序放在一个类中,并将方法作为回调传递(参见print_contents),以下是直接的from the docs

    class App(Frame):
      def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
    
        self.entrythingy = Entry()
        self.entrythingy.pack()
    
        # here is the application variable
        self.contents = StringVar()
        # set it to some value
        self.contents.set("this is a variable")
        # tell the entry widget to watch this variable
        self.entrythingy["textvariable"] = self.contents
    
        # and here we get a callback when the user hits return.
        # we will have the program print out the value of the
        # application variable when the user hits return
        self.entrythingy.bind('<Key-Return>',
                              self.print_contents)
    
      def print_contents(self, event):
        print("hi. contents of entry is now ---->",
              self.contents.get())
    

    2。对你的状态进行 Curry 回调

    您还可以使用 Python 的 functional programming constructs 对全局变量进行柯里化函数,然后将柯里化函数作为回调传递。

    import functools
    
    global_var = {}
    
    def callback(var, event):
      pass
    
    #...
    root.bind('<Key>', functools.partial(callback, global_var))
    

    虽然这可能不是你想要的。

    3。使用全局变量

    有时,全局变量是可以的。

    4。重新架构以提高整洁度和可读性

    但是,您绝对不必在回调中构建程序。

    事实上,我建议您创建一套包含各种有效和无效输入的测试,并创建一个Calculator 类或函数,该类或函数接受 RPN 命令的字符串输入并返回一个值。这很容易在没有 tkinter 接口的情况下进行测试,并且会更加健壮。

    然后,使用您的回调构建一个字符串,并将其传递给您的Calculator

    如果您想要增量计算(即,您正在构建一个模拟器),那么只需让您的计算器接受单个标记而不是整个方程,但设计仍然相似。然后将所有状态封装在Calculator 中,而不是全局封装。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2015-12-21
      • 1970-01-01
      • 2019-04-04
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多