getting a dictionary of class variables and values

[亡魂溺海] 提交于 2019-12-03 02:26:47

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

>>> class A:
...     a = 3
...     b = 5
...     c = 6
... 
>>> {key:value for key, value in A.__dict__.items() if not key.startswith('__') and not callable(key)}
{'a': 3, 'c': 6, 'b': 5}

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

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

Something like this?

  class A(object):
      def __init__(self):
          self.a = 3
          self.b = 5
          self.c = 6

  def return_class_variables(A):
      return(A.__dict__)


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

which gives

{'a': 3, 'c': 6, 'b': 5}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!