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

6

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
  • 3,618
  • 3
  • 31
  • 74
Mazdak
  • 100,514
  • 17
  • 155
  • 179
1

Try this:

In [5]: [x for x in dir(a) if not x.startswith('__')]
Out[5]: ['BAR', 'FOO']
NarūnasK
  • 4,061
  • 6
  • 43
  • 69