On 14/09/06, Chris Hengge <[EMAIL PROTECTED]> wrote: > The deitel book has a note on page 229: > Failure to specify an object reference (usually called self) as the > first parameter in a method definition causes fatal logic errors when > the method is invoked at runt-ime. > > Now I've got methods all over the place among several scripts that don't > use self, and each other works fine as I'd expect.
It depends whether you're writing class methods or not. I could do this, for example: def increment(x): return x+1 and that would be fine, with no self parameter. It's just a standalone function. OTOH, I might decide I want to write my own integer wrapper. class MyInt(object): def __init__(self, i): self.value = i I would create an instance of MyInt like so: i = MyInt(3) The parameter 3 gets passed to __init__ as 'i'. If I left out 'self', python would complain that __init__ only takes one argument and I've given it two. I could define a MyInt method like this: def increment(self): self.value = self.value + 1 thus: >>> i.increment() >>> i.increment() >>> print i.value 5 How would you write increment() without a self parameter? You need some way of referring to the "value" attribute of the instance. If you just write "value = value + 1", python will think you are talking about a local variable, and complain because it can't find one with that name. If you write: def increment(): self.value = self.value + 1 then you're referring to this variable called "self", but where is it coming from? There's no global variable "self", it's not one of the parameters to the method, and you're not defining it in the method. Does that help at all? -- John. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor