[Tutor] Listing all of an instances variables
Karl Pflästerer
khp at pflaesterer.de
Sat Oct 8 19:13:27 CEST 2005
On 8 Okt 2005, matthew.williams at cancer.org.uk wrote:
> Class SomeClass:
> def __init__(self,a,b):
> self.a = a
> self.b = b
>
> def report(self):
> for i in dir(self):
> print self.i
>
> <Error Traceback......>
>
>
> This is where I run into problems: How do I return all of the variables
> in an instance?
You can use the `__dict__' method.
>>> class Someclass (object):
def __init__(self,a,b):
self.a = a
self.b = b
def report(self):
for k, v in self.__dict__.items():
print "Variable %s -> %s" % (k, v)
... ... ... ... ... ... ... >>>
>>> c = Someclass(1,2)
>>> c.report()
Variable a -> 1
Variable b -> 2
>>> c.c = 3
>>> c.report()
Variable a -> 1
Variable c -> 3
Variable b -> 2
>>>
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list