newbie: self.member syntax seems /really/ annoying
Chris Mellon
arkanes at gmail.com
Wed Sep 12 11:34:48 EDT 2007
On 9/12/07, Charles Fox <charles.fox at gmail.com> wrote:
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using. That's
> still kind of annoying though.
>
> The s.varname approach still makes numerical code much harder to read.
>
> I had a nasty bug with the boilerplate approach when forgetting to
> reassign some of the variables back to members (self.a=a). And that's
> a lot of boilerplate you need -- I thought the python way was to
> minimize redundant code? (Ditching header files and curley brackets
> was a main reason for me coming here).
>
> I see the argument for making self explicit -- what would be wrong
> with just .a instead of self.a though? That's still explicit but much
> easier to read. (I think I've seen that somewhere else, is it C#?)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
This is terrible and horrible, please don't use it. That said,
presenting the magic implicit_self context manager!
from __future__ import with_statement
import sys
class implicit_self(object):
def __init__(self, obj):
self.obj = obj
def __enter__(self):
local = sys._getframe(1).f_locals
local.update(self.obj.__dict__)
def __exit__(self, exc, obj, tb):
local = sys._getframe(1).f_locals
for k in self.obj.__dict__:
setattr(self.obj, k, local[k])
if __name__ == '__main__':
class Test(object):
pass
t = Test()
t.a = 10
t.b = 20
with implicit_self(t):
print a
print b
a = 40
b = a * 2
print t.a
print t.b
More information about the Python-list
mailing list