On Sun, 23 May 2010 15:40:13 -0400 Alex Hall <mehg...@gmail.com> wrote:
> Hello all, > I know Python reasonably well, but I still run into basic questions > which those over on the other python list request I post here instead. > I figure this would be one of them: > Why would this not work: > > class c(object): > def __init__(self, arg1, arg2): > self.arg1=arg1 > self.arg2=arg2 > > def doSomething(self, arg3=self.arg1): > ... > > The above results in an error that "name 'self' is not defined". Why > can I not set the default values of a method's arguments to class vars > like that? Thanks! Python gives you the answer (I'm not kidding): "name 'self' is not defined". "self" is not a magic name in python, unlike in some other languages, automagically receiving a value. It is just a name you can use for anything, like "self=1". A *convention* tells that this name is used for the *target* of a message. For instance: l = [3,1,2] l.sort() calls sort on the target l, which becomes the object on which sort applies. Right? Then, python magically (this is the only magic) adds l as first argument to the method sort of the list class, at call time. If sort were defined in python, its header could look like: def sort(target_list, compare_function=None): The convention requires "target_list" to be rather called "self". In your code, nowhere is a variable called "self" defined, before you try to use it. Since this happens in a class def, it should be first defined outside (probably in the global scope). If you write "self=1" somewhere before the class def, python will stop complaining about "self"... but it will complain about "arg1"! A solution for what I guess you're trying to do is: def doSomething(self, arg3=None): if arg3 is None then arg3=self.arg1 The reason is that your default value, not only is not a constant, but is a variable depending on the actual instance, at call time. The only handle available to address an instance is precisely as target of a method call. So, you can only define something (here a default value) that depends on the instance from *inside* a method body, where the handle exists (magically brought by python). Hope it's clear. Denis ________________________________ vit esse estrany ☣ spir.wikidot.com _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor