Accessing class instance variables with vars().

Peter Abel p-abel at t-online.de
Thu Feb 6 17:41:59 EST 2003


Anton Muhin <antonmuhin at sendmail.ru> wrote in message news:<b1r1cs$v5o$1 at news.peterlink.ru>...
> Arcady Genkin wrote:
> > How would I make the following code print both class variable 'foo'
> > and the local variable 'bar' through a variable mapping?
> > 
> > class A:
> >     foo = 1
> >     def show( self ):
> >         bar = 2
> >         print '%(foo)d %(bar)d' % vars(self)
> > 
> > This does not work since vars(self) returns an empty dictionary.
> > 
> > Many thanks in advance,
> 
> There might be minor bug: note that bar *isn't* member of an instance, 
> it's just a temporal variable. You might want it this way:
>
Not really. I think he wanted to say bar, because he wrote
  "local variable"
see above.

> [snipped]
> def show(self):
>      self.bar = 2 # Note *self.*
>      print "%(bar) bar only, for foo see other posts" % vars(self)
> 
> HTH,
> Anton.
Depends on what you want.
If you want self.bar take vars(self).
If you want bar take vars().
Regards
Peter




More information about the Python-list mailing list