简体   繁体   English

当对象在Python中不具有“ __iter__”功能时,如何显示所有方法和数据

[英]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列出所有属性
  • the for ... in creates a generator which returns each attribute name for ... in创建一个生成器,该生成器返回每个属性名称
  • the getattr retrieves the value of the attribute for the object getattr检索对象的属性值
  • the % interpolates those values into a string %这些值插入字符串
  • the ''.join concatenates all the strings into a single one ''.join将所有字符串连接成一个字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM