-1

Class example:

class Cls1:
  a=10
  b=20

Expected output:

{a:10, b:20}

Note: I can instantiate the class and use vars function to get the above output. But I need to see the class variable values without instantiating the class.

variable
  • 6,123
  • 5
  • 52
  • 127

2 Answers2

3

Try Cls1.__dict__ or vars(Cls1)

You can separate them with __

>>> {k: v for k, v in vars(Cls1).items() if not k.startswith("__")}        
{'a': 10, 'b': 20}
Mohammad Jafari
  • 1,348
  • 10
  • 14
2

They're class attributes, not instance attributes.

>>> Cls1.a
10
>>> Cls1.b
20

Classes have other attributes besides the ones you define explicitly, so vars(Cls1) will give you a lot of stuff you don't want. Best to be explicit:

>>> {k: v for k, v in vars(Cls1).items() if k in ['a', 'b']}
{'a': 10, 'b': 20}

or

>>> {k: getattr(Cls1, k) for k in ['a', 'b']}

Classes aren't supposed to be used as containers. If you want a container, use a dict in the first place.

chepner
  • 446,329
  • 63
  • 468
  • 610