Python的 - 引用变量不存在

问题描述:

我正在学习Python中Tkinter的包,我不明白下面的代码:Python的 - 引用变量不存在

import tkinter as tk 

class Application(tk.Frame): 
    def __init__(self, master=None): 
     super().__init__(master) 
     self.pack() 
     self.create_widgets() 

    def create_widgets(self): 
     self.hi_there = tk.Button(self) 
     self.hi_there["text"] = "Hello World\n(click me)" 
     self.hi_there["command"] = self.say_hi 
     self.hi_there.pack(side="top") 

     self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) 
     self.quit.pack(side="bottom") 

    def say_hi(self): 
     print("hi there, everyone!") 

root = tk.Tk() 
app = Application(master=root) 
app.mainloop() 

据我了解self指的是类代码时说: self.hi_there我期望这个类中的全局变量必须先声明。 hi_there如何创建?

__init__方法中有什么“master = None”的用法?如果我跳过=None部分,那么它会不会是相同的,因为我做的是app = Application(master=root)

+0

不知道你为什么认为它们不存在。 –

+0

它在'self.hi_there = tk.Button(self)'创建。 – Ryan

+0

它被创建为一个全局变量?这里的自我意味着什么?为什么不简单地把“hi_there = tk.Button(self)” – akerbeltz

self指的是实例。 self.hi_there是一个实例变量。通过做app = Application(master=root)您创建Application的实例并将其保存到app。在你的情况下,selfapp

在创建属性之前,您不需要声明属性(尽管在__init__中创建它们被认为是一种很好的做法)。

考虑例如:

class A() 
    pass 

a = A() 
a.prop = 2 
print(a.prop) #=> 2 

关于master=None - 事实上,你可以,如果它是你的代码只使用master,你知道你将它传递。

+0

但在这个例子中,它不会改变任何东西,如果我只是创建像'hi_there = tk.Button(self)'而不是'self.hi_there = tk.Button(self)'这样的小部件,那么这里的自我意味着什么? – akerbeltz

+0

@akerbeltz对不起,我没有关注。你的问题是什么? –

+0

我不知道如何解释,我试着没有自己的代码在每个部件的代码,它不会改变任何东西(我注意到)。为什么不简单地把“hi_there = tk.Button(self)”? – akerbeltz

self指的是类的实例,并为此self.hi_there = foo将创建一个新的实例变量,并将其分配给foo,如:

class Test: 
    def __init__(self): 
     self.foo = 'bar' 

a = Test() 
print(a.foo) 

# output: 
# bar 

而且master=None在默认None值设置为master,除非你供应该值,例如:

app = Application() # here master will be None 
app = Application(master=root) # here master will be root 

This可以与任何功能一起使用,这里是另一个例子:

def plus(num=0): 
    return num+num 

print(plus(1)) 
print(plus()) 

# output: 
# 2 
# 0