Accessing class instance variables with vars().

Peter Abel p-abel at t-online.de
Wed Feb 5 07:04:48 EST 2003


Arcady Genkin <agenkin at thpoon.com> wrote in message news:<86vfzzqwv4.fsf at tea.thpoon.com>...
> 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)
          print '%(foo)s %(bar)s'%dict(vars().items()+vars(A).items())
> 
> This does not work since vars(self) returns an empty dictionary.
> 
> Many thanks in advance,

The replacement of the print line should work.
May be there's still a better possibility to join 2 dictionaries.

BTW, if want to see the instance attributes too append vars(self).items().

Regrads
Peter




More information about the Python-list mailing list