[英]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 : (1):dir(对象)为
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): (2):
b=eval(a)
(3)and it became a list of all method : (3)它成为所有方法的列表:
['__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 : (3)然后显示对象的方法,所有代码为:
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 谢谢
s += str(i)+':'+str(getattr(object, i))
s = ''.join('%s: %s' % (a, getattr(o, a)) for a in dir(o))
dir
lists all attributes dir
列出所有属性 for ... in
creates a generator which returns each attribute name for ... in
创建一个生成器,该生成器返回每个属性名称 getattr
retrieves the value of the attribute for the object getattr
检索对象的属性值 %
interpolates those values into a string %
这些值插入字符串 ''.join
concatenates all the strings into a single one ''.join
将所有字符串连接成一个字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.