获取类变量和值的字典 [英] getting a dictionary of class variables and values
问题描述
我正在使用一个方法来返回所有的类变量作为键和值作为字典的值,例如我有:
first.py
p> A类:
a = 3
b = 5
c = 6
然后在second.py中,我应该能够调用一个方法或者一些将返回这样的字典的东西。
先导入
dict = first.return_class_variables()
dict
那么dict将是这样的:
{'a':3,'b':5,'c':6}
这只是一个场景来解释这个想法,当然我不期望它是那么容易,但我会喜欢如果有如何处理这个问题的想法,就像 dict 可以用于设置类变量值,方法是将变量,值组合作为键值传递给字典。
解决方案需要过滤掉函数和内置类的属性。
>> A类:
... a = 3
... b = 5
... c = 6
...
>>>如果没有key.startswith('__')和不可调用(key)}
{'a':3,'c':6, 'b':5}
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 in the second.py i should be able to call maybe a method or something that will return a dictionary like this
import first dict = first.return_class_variables() dict
then dict will be something like this:
{'a' : 3, 'b' : 5, 'c' : 6}
This is just a scenario to explain the idea, of course i don't expect it to be that easy, but i will love if there are ideas on how to handle this problem just like dict can be used to set a class variables values by passing to it a dictionary with the variable, value combination as key, value.
解决方案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}
这篇关于获取类变量和值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!