Pla*_*aix 13 python dictionary class class-variables
我正在研究一种方法,将所有类变量作为键和值返回为字典的值,例如我有:
first.py
class A:
a = 3
b = 5
c = 6
Run Code Online (Sandbox Code Playgroud)
然后在second.py中,我应该可以调用一个方法或者一些会返回这样的字典的东西
import first
dict = first.return_class_variables()
dict
Run Code Online (Sandbox Code Playgroud)
然后dict将是这样的:
{'a' : 3, 'b' : 5, 'c' : 6}
Run Code Online (Sandbox Code Playgroud)
这只是一个解释这个想法的场景,当然我不希望它那么容易,但我会喜欢如果有关于如何处理这个问题的想法就像dict可以用来设置一个类变量值将变量,值组合作为键,值传递给它.
afk*_*ion 24
您需要过滤掉函数和内置类属性.
>>> 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}
Run Code Online (Sandbox Code Playgroud)