8

How would I get a list of attributes in a class? For example:

class Test:
    def __init__(self,**kw):
        for k,v in kw.items():
            setattr(self,k,v)
x = Test(value="hello",valueTwo="world")
print(dir(x))

I've done that and it seems to print the keys but, it also prints extra stuff like:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__','value','valueTwo']

is there another way to do this so it just gets the keys/values.

Juergen
  • 12,378
  • 7
  • 39
  • 55
user2925490
  • 512
  • 2
  • 5
  • 11
  • possible duplicate of [Python - Get Instance Variables](http://stackoverflow.com/questions/109087/python-get-instance-variables) – OdraEncoded Oct 27 '13 at 17:00

1 Answers1

22

Use x.__dict__:

>>> x.__dict__
{'value': 'hello', 'valueTwo': 'world'}

>>> [ v for k,v in x.__dict__.items() if '__' not in k and 'object at' not in k ]
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504