问题
I found this example of a simple tkinter class. The example works with either
'frame' or 'self.frame'
Why can or would I safely omit 'self'?
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(
frame, text="QUIT", fg="red", command=frame.quit
)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print "hi there, everyone!"
root = Tk()
app = App(root)
root.mainloop()
root.destroy() # optional; see description below
回答1:
In general, it's more efficient to use a local variable like frame
rather than an object attribute like self.frame
. You should only use an object attribute when you need to be able to refer to the object after the method that created it returns.
In Python, objects that are stored in local variables get garbage-collected once the function or method returns, but that's not a problem here. The Frame object itself will be persistent because it's linked to the master object you pass to __init__()
.
回答2:
You can omit self
for most case, except for self.say_hi
. Otherwise, say_hi
references global function, not a method.
def __init__(self, master):
frame = Frame(master)
frame.pack()
button = Button(frame, text="QUIT", fg="red", command=frame.quit)
button.pack(side=LEFT)
hi_there = Button(frame, text="Hello", command=self.say_hi)
hi_there.pack(side=LEFT)
self.frame
/ frame
both can be used as long as the frame object is referenced only in a method. If it is used in another method, it should be qualified as self.frame
.
回答3:
You can omit self
before frame
because you pass in reference to it into the Button
which gets stored as self.button
(presumably Button
holds a reference to the frame for you).
This ensures that your frame
will not be garbage collected onece you're out of scope of __init__
as only objects that are not referred anywhere get destroyed.
In this example you have no use for frame
outside of self.button
so no point storing additional reference to it in self.frame
.
As mentioned in other answers you only need self
if you will want to reference something directly later in relation to your object instance.
来源:https://stackoverflow.com/questions/27374541/when-can-i-omit-self