Datenattribute und Properties ausgeben

   1 import inspect
   2 
   3 def get_attributes(obj, public_only=True):
   4     attrs = inspect.getmembers(obj, lambda o: not inspect.isroutine(o))
   5     if public_only:
   6         return [x for x in attrs if x[0][0] != "_"]
   7     else:
   8         return attrs

Die Attribute werden als Liste mit Tuples, die Name und Wert, enthalten zurückgegeben. Wird der Parameter public_only auf False gesetzt, werden auch private und Spezialattribute wie __dict__ zurückgeliefert.

Beispiel:

   1 >>> class Test(object):
   2 ...     def __init__(self):
   3 ...             self.value = "Test"
   4 ...             self._hidden = "Spam"
   5 ...
   6 >>> get_attributes(Test())
   7 [('value', 'Test')]
   8 >>> get_attributes(Test(), False)
   9 [('_hidden', 'Spam'),
  10  ('__class__', <class '__main__.Test'>),
  11  ('__delattr__', <method-wrapper object at 0xb7e0d2ac>),
  12  ('__dict__', {'_Test__hidden': 'Spam', 'value': 'Test'}),
  13  ('__doc__', None),
  14  ('__getattribute__', <method-wrapper object at 0xb7e0d82c>),
  15  ('__hash__', <method-wrapper object at 0xb7e0d32c>),
  16  ('__module__', '__main__'),
  17  ('__repr__', <method-wrapper object at 0xb7e0d2cc>),
  18  ('__setattr__', <method-wrapper object at 0xb7e0de6c>),
  19  ('__str__', <method-wrapper object at 0xb7e0d9cc>),
  20  ('__weakref__', None),
  21  ('value', 'Test')]


Entnommen aus Herausfinden der Datenattribute und Properties eines Objektes

Datenattribute und Properties ausgeben (last edited 2009-06-17 16:14:20 by localhost)