“自己"是什么时候必需的? [英] When is "self" required?
问题描述
我使用类的时间很短,当我编写一个方法时,我让所有变量都引用 self,例如self.foo.
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.
然而,我正在阅读 wxPython in Action 一书,注意到self"并没有一直使用.例如:
However, I'm looking through the wxPython in Action book and notice that "self" isn't used all the time. For example:
import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
下面的那个确实使用了self".
The one below does use "self".
import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
如果我没记错的话,self"是对类的特定实例的引用,那么什么时候不需要呢?是否有一般的经验法则?
If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?
推荐答案
您使用 self.attribute
来引用当前实例的属性.
You use self.attribute
to reference an attribute of your current instance.
您使用 wx.Frame.__init__()
来引用父类的方法.
You use wx.Frame.__init__()
to reference a method of the parent class.
如果您只引用您所在的方法(函数)的本地名称(变量),则不要使用 self
.
You don't use self
if you only reference a local name (variable) of the method (function) you are in.
这些不是经验法则",因为没有例外.
These are not "rules of thumb," because there are no exceptions.
在这个特定示例中可能让您感到困惑的是,面板似乎只是构造函数中的一个本地名称,因此一旦您的构造函数返回,面板就会消失.
What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.
如果您查看wx.Panel
的文档,您会看到它的 构造函数将面板附加到父窗口,因此它将继续存在, 即使在构造函数返回之后.
If you look at the documentation to wx.Panel
, though, you will see that its constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.
魔法:)
这篇关于“自己"是什么时候必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!