[Tutor] Interesting problem

Kent Johnson kent37 at tds.net
Thu Jun 23 20:29:13 CEST 2005

Smith, Jeff wrote:
> Consider a class with a lt of properties.  I would like a member
> function which generates a dictionary where the keys are the property
> names and the values are the property values?
> Is this clear?

No, actually :-)

Do you want the properties of the class (which are typically the methods of the class) or properties of an instance of the class (which is typically instance variables).

I'm guessing you want to see the instance values. These are already available in a dictionary, the __dict__ attribute of the instance:

 >>> class T:
 ...   def __init__(self, x, y):
 ...     self.x = x
 ...     self.y = y
 ...   def show(self):
 ...     print 'x =', self.x, 'y =', self.y

dir(T) shows all the attributes of T, including inherited attributes:

 >>> dir(T)
['__doc__', '__init__', '__module__', 'show']

 >>> t=T(1, 2)

dir works for instances too. Notice it shows all accessible attributes which includes attributes of the class:

 >>> dir(t)
['__doc__', '__init__', '__module__', 'show', 'x', 'y']

But I think __dict__ is what you want:

 >>> t.__dict__
{'y': 2, 'x': 1}


More information about the Tutor mailing list