HorstThu Nov 13 13:15:55 PST 2003
In response to: > Date: Thu, 13 Nov 2003 09:49:34 -0800 > From: Rob Hudson <rob at euglug.net> ... > > So, is this the workaround?: > > class myclass: > def __init__(self, value): > self.value = value > def myfunc(self, arg=None): > if arg is None: > arg = self.value > print arg > > This seems tedious to me, but maybe that's the way it is. Any tricks to > do this more easily? ... Rob, I think your alternative is the common way. I used the debugger to study the problem: When the module is loaded (before executing the top-level code) the class is compiled to byte code, and at that time there is not yet an instance of 'self'. Even static Class members don't seem to be recognized at that point (!?) During the compilation to byte code each function's 'hidden' dictionary gets populated -- our relevant key:val pair is {..., 'func_defaults' : (dflt1, dflt2,...), ...} My function trick() does the trick. It re-assigns the default arguments; for demo purposes I left it commented out in the constructor. But it's a hack, and I wouldn't use it. Still, it's nice to have a language let's you look under the hood :-) - Horst ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import pdb globVar = "Boo" class MyClass: qs = 'quasiStatic' def __init__(self, val): self.value = val #self.trick() def myfun(self, arg=globVar): print arg def trick(self): MyClass.myfun.im_func.func_defaults = (self.value, ) x = MyClass('myVal') x.myfun(x.value) # pdb.set_trace() # look at commands vars(), locals(), globals() globVar = MyClass.qs print globVar x.myfun() # no effect yet on MyClass.myfun(arg=globVar) x.trick() # this does the trick, but I don't recommend it x.myfun() # default argument is now a class member ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _______________________________________________ Think_python mailing list Think_python at efn.org http://mailman.efn.org/mailman/listinfo/think_python