getting a dictionary of class variables and values

后端 未结 3 1843
余生分开走
余生分开走 2021-02-04 02:39

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条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 03:22

    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}
    

提交回复
热议问题