how to show all method and data when the object not has "__iter__" function in python
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 c开发者_运维百科ode running .
thanks
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
s += str(i)+':'+str(getattr(object, i))
精彩评论