Python: printing __dict__: is it possible to print in the same order as in a list in a class?

Sorry, probably a stupid question, but I can not find the answer. Context: I'm new to python and doing simple rpg. The class will have some basic rpg attributes, such as

class Character(Card):
    def __init__(self, str, dex, con, int, wis, char):
        self.str = str
        self.dex = dex
        self.con = con
        self.int = int
        self.wis = wis
        self.char = char

Since I will assign values ​​depending on the character class, I would like to make a general debugging method so that I can later print them for this class. My question is: is there an easy way to print them later (str, dex, con ...).

I'm going to go with the base

def printClass(self):
    attrs = an.__dict__
    print ', ' '\n'.join("%s: %s" % item for item in attrs.items()) 

which prints them in a specific order dex: 2, int: 4, char: 6, wis: 5, str: 1, con: 3

but if I missed something to keep it in order, I would like help / advice

* : , rogue = Character (1,2,3,4,5,6), rogue.str, rogue.dex( , : str, dex, con, int, wis, char)

+4
3

, , . , , , . , , __str__(self) Character

class Character(object): # Changed this since I don't know how class 'Card' looks like
    def __init__(self, str, dex, con, int, wis, char):
        self.str = str
        self.dex = dex
        self.con = con
        self.int = int
        self.wis = wis
        self.char = char

    def __str__(self):
        return "str: {}, dex: {}, con: {}, int: {}, wis: {}, char: {}".format(self.str, self.dex, self.con, self.int, self.wis, self.char)

# Testing
list_of_characters = [Character(1, 2, 3, 4, 5, "A"), Character(9, 8, 7, 6, 5, "B")]

for e in list_of_characters:
    print e

:

str: 1, dex: 2, con: 3, int: 4, wis: 5, char: A
str: 9, dex: 8, con: 7, int: 6, wis: 5, char: B

Edit:

, Python . , str int . - .

+4

, :

def printClass(self, order):
    attrs = an.__dict__
    for i in order:
        print attrs[i]

['foo', 'bar']...

, an.order

+2

Python dict does not keep order. So the short answer is no, you cannot print your dict attribute in order. But maybe it will be useful, you can sort the keys before printing:

def printClass(self):
    attrs = an.__dict__
    print ', ' '\n'.join("%s: %s" % item for item in sorted(attrs.items(), key=lambda i: i[0])) 

It will print: char: 6, con: 3, dex: 2, int: 4, str: 1, wis: 5

+1
source

All Articles