Accessing class instance variables with vars().
Anton Muhin
antonmuhin at sendmail.ru
Wed Feb 5 07:51:39 EST 2003
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:
[snipped]
def show(self):
self.bar = 2 # Note *self.*
print "%(bar) bar only, for foo see other posts" % vars(self)
HTH,
Anton.
More information about the Python-list
mailing list