Display all properties with reflection

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Oct 20 18:42:34 CEST 2007

En Sat, 20 Oct 2007 06:03:55 -0300, sccs cscs <zorg724 at yahoo.fr> escribi�:

> Hello,
> I like create a methode that display all the properties of an instance  
> of classe with their value.
> I try the following code: see     def __str__ (self) methode.
> But it displays only the instance attributes values not the properties  
> and their value.
> In pseudo-code:
> For Each Properties :
>    print  property_name,  property_value
> It is possible ? Where is the collection of properties into the Python  
> Object Metamodele?

Is this what you want, using dir()?

py> class A(object):
...   x = 1
...   @property
...   def y(self): return 2
py> a=A()
py> a.z=3
py> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',  
'__hash__', '__init__', '__module__', '__new__', '__reduce__',  
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'x',  
'y', 'z']
py> for name in dir(a):
...   if name[:1]=='_': continue
...   print name, getattr(a,name)
x 1
y 2
z 3

You may want to filter out some values, methods by example. If you usually  
don't store functions as attributes, checking if the attribute itself has  
a __call__ attribute may be enough:

py> class B(A):
...   def method1(self): pass
...   @classmethod
...   def method2(cls): pass
...   @staticmethod
...   def method3(): pass
...   def foo(self):
...     self.some_var = 1
...     def some_function(a):
...       return "hello!"
...     self.some_function = some_function
py> b=B()
py> b.foo()
py> dir(b)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',  
'__hash__', '__init__', '__module__', '__new__', '__reduce__',  
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__',  
'foo', 'method1', 'method2', 'method3', 'some_function', 'some_var', 'x',  
py> for name in dir(b):
...   if name[:1]=='_': continue
...   value = getattr(b,name)
...   if hasattr(value, '__call__'): continue
...   print name,'=',value
some_var = 1
x = 1
y = 2

Gabriel Genellina

More information about the Python-list mailing list