簡體   English   中英

當對象在Python中不具有“ __iter__”功能時,如何顯示所有方法和數據

[英]how to show all method and data when the object not has “__iter__” function in python

我想辦法:

(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):

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__'

那么如何使我的代碼運行。

謝謝

s += str(i)+':'+str(getattr(object, i))
s = ''.join('%s: %s' % (a, getattr(o, a)) for a in dir(o))
  • dir列出所有屬性
  • for ... in創建一個生成器,該生成器返回每個屬性名稱
  • getattr檢索對象的屬性值
  • %這些值插入字符串
  • ''.join將所有字符串連接成一個字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM