[英]Listing all the variables in a Python class
I've made a class, and after the program has finished running, I want to list all the variables I have kinda like so我做了一个类,在程序运行完成后,我想列出我拥有的所有变量
var1: val
var2: val
etc
my class looks like this我的班级看起来像这样
class character:
name = 'Player1'
level = 1
str = 100
con = 80
sta = 150
critchance = 0.1
critdmg = 0.5
# for battle
hp = con * con
thoughness = math.sqrt(sta)
You can use dictionary comprehension (assuming Python 2.6+) to extract the variables from the class' __dict__
:您可以使用字典理解(假设 Python 2.6+)从类的__dict__
提取变量:
print({k: v for k, v in character.__dict__.items() if not k.startswith('__')})
>> {'con': 80, 'level': 1, 'critchance': 0.1, 'sta': 150,
'str': 100, 'name': 'Player1', 'critdmg': 0.5}
Just keep in mind that in the example that you provided, these are class variables rather than instance variables.请记住,在您提供的示例中,这些是类变量而不是实例变量。
Is something like this what you are looking for?你正在寻找这样的东西吗?
for var in dir(character):
if var[:2] != '__':
print '%s:' % var, getattr(character, var)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.