[Tutor] Newbie question on Self, Master and others.
alan.gauld@bt.com
alan.gauld@bt.com
Tue, 22 Aug 2000 12:15:29 +0100
> I'm some experiance with VB and am new to Python. In
> reviewing some code examples I've come across the "def
> __init__()" function with several different, what seems to me
> are argument options. IE: self, master, master=None. Would
init() is the Python constructor mechaniusm(which ISTR doesn't
exist in VB!). When you create a new object the init method gets called
automagically.
The self, master, etc are all variables like any other but any
function(method) defined within a class causes Python to use the
first parameter as a placeholder for the object.
Thus:
class Foo:
def __init__(bar):
# do something
def jiggle(baz,spam):
# do some other thing
f = Foo() # f gets a reference to the new FOO object
# Foo.__init__(f) gets called behind the scenes
# thus bar gets the value of f, which is the new object
f.jiggle('burble') # calls Foo.jiggle(f,'burble') in a friendly way
By *convention* the first parameter in a method is called 'self'
(because it will be populated by Python with a reference to
the current object - the one owning the method. Thus normally
you'd see the above example as:
class Foo:
def __init__(self):
# do something
def jiggle(self, spam):
# do some other thing
f = Foo()
f.jiggle('burble')
The master=None bit simply says that master is a parameter,
which if no value is provided it will take the value None.
ie:
>>> def sayHello(name='World'):
... print 'Hello ' + name
...
>>> sayHello('Alan') # I provide a value
Hello Alan
>>> sayHello() # no value so use default
Hello World
>>>
This stuff is covered in my online tutor at:
http://www.crosswinds.net/~agauld/
Look under 'modules & functions' for the default args and
under 'OOP' for __init__() stuff.
HTH,
Alan G.