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?

Sadiksha Gautam
  • 5,032
  • 6
  • 40
  • 71
  • 1
    Any reason you're using an object's attributes to store the information, and not actually using a dict contained in the object? – Jon Clements Jul 10 '12 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__. – Simon Jul 10 '12 at 11:11

1 Answers1

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]
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 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. – Sadiksha Gautam Jul 12 '12 at 07:19