Accessing class instance variables with vars().
Andrew Bennetts
andrew-pythonlist at puzzling.org
Wed Feb 5 07:35:03 EST 2003
On Wed, Feb 05, 2003 at 04:04:48AM -0800, Peter Abel wrote:
> 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.
I think I'd probably join them with:
d = vars()
d.update(vars(A))
print '....' % d
But then it's not a one-liner anymore.
-Andrew.
More information about the Python-list
mailing list