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)
?
答
self
指的是实例。 self.hi_there
是一个实例变量。通过做app = Application(master=root)
您创建Application
的实例并将其保存到app
。在你的情况下,self
是app
。
在创建属性之前,您不需要声明属性(尽管在__init__
中创建它们被认为是一种很好的做法)。
考虑例如:
class A()
pass
a = A()
a.prop = 2
print(a.prop) #=> 2
关于master=None
- 事实上,你可以,如果它是你的代码只使用master
,你知道你将它传递。
答
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
不知道你为什么认为它们不存在。 –
它在'self.hi_there = tk.Button(self)'创建。 – Ryan
它被创建为一个全局变量?这里的自我意味着什么?为什么不简单地把“hi_there = tk.Button(self)” – akerbeltz