getting the state of an object

Chris Angelico rosuav at gmail.com
Sun Oct 7 07:11:03 EDT 2012


On Sun, Oct 7, 2012 at 7:50 PM, Franck Ditter <franck at ditter.org> wrote:
> def foo(self) :
>     (a,b,c,d) = (self.a,self.b,self.c,self.d)
>     ... big code with a,b,c,d ...
>

This strikes me as ripe for bug introduction. There's no problem if
you're just reading those values, and mutating them is equally fine,
but suddenly you need a different syntax for modifying instance
members.

def foo(self) :
    (a,b,c,d) = (self.a,self.b,self.c,self.d)
    e = a+b
    c.append(1234)
    d=self.d = 57   # Oops, mustn't forget to assign both!


Since Python lacks the extensive scoping rules of (say) C++, it's much
simpler and safer to be explicit about scope by adorning your instance
variable references with their "self." tags. There's a guarantee that
you can use "self.a" in any situation where you want to manipulate
that member, a guarantee that's not upheld by the local "a".

In theory, I suppose you could use a C-style preprocessor to help you.

class Foo(object):
  #define asdf self.asdf
  #define qwer self.qwer

  def __init__(self,a,q):
    asdf=a; qwer=q

  def __repr__(self):
    return "Foo(%s,%s)"%(asdf,qwer)

This is not, however, Pythonic code. But if you made some kind of
better declaration than #define, and used a preprocessor that
understood Python indentation rules and flushed its token list at the
end of the class definition, you could perhaps make this look
not-ugly. I still wouldn't recommend it, though.

ChrisA



More information about the Python-list mailing list