List attributes of an object

MadSc13ntist picture MadSc13ntist · Apr 20, 2010 · Viewed 689.2k times · Source

Is there a way to grab a list of attributes that exist on instances of a class?

class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))

The desired result is that "multi, str" will be output. I want this to see the current attributes from various parts of a script.

Answer

Roger Pate picture Roger Pate · Apr 20, 2010
>>> class new_class():
...   def __init__(self, number):
...     self.multi = int(number) * 2
...     self.str = str(number)
... 
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])

You may also find pprint helpful.