Petter Petter
Petter Petter

Reputation: 103

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)

Upvotes: 1

Views: 64

Answers (2)

Tonechas
Tonechas

Reputation: 13743

Is something like this what you are looking for?

for var in dir(character):
    if var[:2] != '__':
        print '%s:' % var, getattr(character, var)

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81684

You can use dictionary comprehension (assuming Python 2.6+) to extract the variables from the class' __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.

Upvotes: 1

Related Questions