Skip to content Skip to sidebar Skip to footer

Getting A Dictionary Of Class Variables And Values

I am working on a method to return all the class variables as keys and values as values of a dictionary , for instance i have: first.py class A: a = 3 b = 5 c = 6 Then

Solution 1:

You need to filter out functions and built-in class attributes.

>>>classA:...    a = 3...    b = 5...    c = 6...>>>{key:value for key, value in A.__dict__.items() ifnot key.startswith('__') andnotcallable(key)}
{'a': 3, 'c': 6, 'b': 5}

Solution 2:

Something like this?

classA(object):
      def__init__(self):
          self.a = 3
          self.b = 5
          self.c = 6defreturn_class_variables(A):
      return(A.__dict__)


  if __name__ == "__main__":
      a = A()
      print(return_class_variables(a))

which gives

{'a': 3, 'c': 6, 'b': 5}

Solution 3:

Use a dict comprehension on A.__dict__ and filter out keys that start and end with __:

>>> classA:
        a = 3
        b = 5
        c = 6... >>> {k:v for k, v in A.__dict__.items() ifnot (k.startswith('__')
                                                             and k.endswith('__'))}
{'a': 3, 'c': 6, 'b': 5}

Solution 4:

Best solution and most pythonic is to use var(class_object) or var(self) (if trying to use inside class).

This although do avoids dictionary pairs where the key is another object and not a default python type.

>>> classTheClass():
>>> def__init__(self):
>>>        self.a = 2>>>        self.b = 1>>> print(vars(self))
>>> class_object= TheClass()
{'a'=2, 'b'=1}

Or outside class

>>> vars(class_object)
{'a': 2, 'b': 1}

Post a Comment for "Getting A Dictionary Of Class Variables And Values"