[Tutor] Listing all of an instances variables

Kent Johnson kent37 at tds.net
Mon Oct 10 22:01:54 CEST 2005


Matt Williams wrote:
> Dear List,
> 
> I'm stuck on trying to write a generic 'report' function:
> 
> 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?

If you are trying to show the data attributes of an instance then Karl's suggestion of self.__dict__.items() is probably the best. dir() attempts to show all accessible attributes, which may be instance variables, class methods, class attributes, etc. For example:

 >>> class F(object):
 ...   def __init__(self):
 ...     self.data = 1
 ...   def show(self):
 ...     print 'data =', self.data
 ...
 >>> f=F()
 >>> dir(f)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__'
, '__repr__', '__setattr__', '__str__', '__weakref__', 'data', 'show']
 >>> f.__dict__
{'data': 1}

In this case f.__dict__ is probably what you want, not dir(f). However it's easy to make an example where __dict__ doesn't contain all accessible attributes, for example in a class that defines __slots__:
 >>> class G(object):
 ...   __slots__ = ['data']
 ...   def __init__(self):
 ...     self.data = 1
 ...
 >>> g=G()
 >>> g.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'G' object has no attribute '__dict__'
 >>> dir(g)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__'
, '__setattr__', '__slots__', '__str__', 'data']
 >>> g.__slots__
['data']
 >>>

A class that defines __getattr__ or __getattribute__ could have attributes that don't appear in dir(), __dict__ or __slots__. So in general I think what you want is hard. For common cases __dict__ will work.

Kent































More information about the Tutor mailing list