views:

34

answers:

2

i find a way :

(1):the dir(object) is :

a="['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']"

(2):

b=eval(a)

(3)and it became a list of all method :

['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']

(3)then show the object's method,and all code is :

s=''
a=eval(str(dir(object)))
for i in a:
    s+=str(i)+':'+str(object[i])

print s

but it show error :

KeyError: '__class__'

so how to make my code running .

thanks

+2  A: 
s += str(i)+':'+str(getattr(object, i))
Satoru.Logic
+1  A: 
s = ''.join('%s: %s' % (a, getattr(o, a)) for a in dir(o))
  • dir lists all attributes
  • the for ... in creates a generator which returns each attribute name
  • the getattr retrieves the value of the attribute for the object
  • the % interpolates those values into a string
  • the ''.join concatenates all the strings into a single one
Chris B.