在python中,当对象没有“\uu iter\uuuuu”函数时,如何显示所有的方法和数据

2024-05-01 18:10:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想办法:

(1):dir(object)是:

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']"

(二):

b=eval(a)

(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)然后显示对象的方法,所有代码为:

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

print s

但它显示了错误:

KeyError: '__class__'

所以如何让我的代码运行。你知道吗

谢谢


Tags: reducefieldsdocobjectdirhashdictclass
2条回答
s = ''.join('%s: %s' % (a, getattr(o, a)) for a in dir(o))
  • dir列出所有属性
  • for ... in创建一个生成器,返回每个属性名
  • getattr检索对象的属性值
  • %将这些值插入到字符串中
  • ''.join将所有字符串连接成一个字符串
s += str(i)+':'+str(getattr(object, i))

相关问题 更多 >