5

How to get user-defined class attributes from class instance? I tried this:

class A:
    FOO = 'foo'
    BAR = 'bar'

a = A()

print(a.__dict__)  # {}
print(vars(a))  # {}

I use python 3.5. Is there a way to get them? I know that dir(a) returns a list with names of attributes, but I need only used defined, and as a dict name to value.

danielko
  • 51
  • 1
  • 2

2 Answers2

7

You've defined those variables within the class namespace which haven't propagated into instances. You can use the __class__ attribute of the instance to access the class object, and then use the __dict__ method to get the namespace's contents:

>>> {k: v for k, v in a.__class__.__dict__.items() if not k.startswith('__')}
{'BAR': 'bar', 'FOO': 'foo'}
Pro Q
  • 4,391
  • 4
  • 43
  • 92
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Try this:

In [5]: [x for x in dir(a) if not x.startswith('__')]
Out[5]: ['BAR', 'FOO']
NarūnasK
  • 4,564
  • 8
  • 50
  • 76