inspect attributes of object python

2019-08-27 15:49发布

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条回答
地球回转人心会变
2楼-- · 2019-08-27 16:48

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]
查看更多
登录 后发表回答