0

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?

2
  • 1
    Any reason you're using an object's attributes to store the information, and not actually using a dict contained in the object? Commented Jul 10, 2012 at 11:05
  • I'd suggest a property that returns a dict of the relevant info. If you want quick+dirty, subtract object.__dict__ from your object's .__dict__. Commented Jul 10, 2012 at 11:11

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't solve my problem. I have other buit-in attributes that do not start and end with __. What I want to get is only user specified attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.