Reputation: 1224
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
menubar = wx.MenuBar()
fileMenu = wx.Menu()
viewMenu = wx.Menu()
self.shst = viewMenu.Append(wx.ID_ANY, 'Show statubar',
'Show Statusbar', kind=wx.ITEM_CHECK)
...
I've recently started learning python and wxPython. The above code snipppet is from http://www.zetcode.com/wxpython/menustoolbars/ . I'm trying to get my head around the self.shst variable. Why is it necessary to prefix it with the self keyword ?
From what I read, the self keyword is used in that context in the __init__ method, to "declare" instance variables, but the author has no shst declaration in __init__
Edit In light of your answers I did the following test:
class Test(object):
def __init__(self):
self.x = 20
def func(self):
self.y = 10
def getVal(self):
return self.y
def main():
t = Test()
print t.getVal()
print dir(t)
if __name__ == '__main__':
main()
I am unable to access self.y in the getVal() function, and I don't see y in the output from dir(t). Shouldn't self.y be accessible to every function in the Test class ?
Upvotes: 0
Views: 250
Reputation: 19169
If you did not prefix shst
with self.
, then it would just be a local variable that goes out of scope and is garbage-collected after the method exits. There is no need to declare python class/object members prior to assignment.
Upvotes: 1
Reputation: 599530
There's no necessity to define instance variables in __init__
. They can be defined anywhere. Python is a dynamic langauge, and it is possible to add attributes to an object at any point.
Upvotes: 1