inspect attributes of object python

落花浮王杯 提交于 2020-01-06 20:00:36

问题


I have an object in python like <Person at /project/persons/id>. Now I want to see all the attributes of the person like I have FirstName, LastName and title of the person. What I would like to get is {'FirstName':'Anna', 'LastName': 'Perry', 'Title' : 'Ms.'}.

I tried object.__dict__ but it gives me other built-in attributes as well. I would only like to get user specified attributes. Can anyone help me with this?


回答1:


There's no direct way to get only the user-defined attributes. Often people will use dunder names as a signal:

attrs = {}
for k in dir(my_object):
    if k.startswith("__") and k.endswith("__"):
        continue
    attrs[k] = my_object[k]


来源:https://stackoverflow.com/questions/11411882/inspect-attributes-of-object-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!