Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: printing __dict__ : is it possible to print in the same order as what's listed in the class?

Sorry, probably silly question but can't find the answer.. Context is I'm new to python and doing a simple rpg. Class is going to have some basic rpg attributes like

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'll be assigning the values depending on the character class, I wanted to make a generic debug method to print these out for an given class later. My question is: is there a simple way to print these out in order later (str, dex, con...).

I' about to go with a basic

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

which prints them out in now particular order dex: 2, int: 4, char: 6, wis: 5, str: 1, con: 3

but if i overlooked something to keep it in order, I'd love the help/advice

*Edit: To clarify if i made rogue = Character(1,2,3,4,5,6), i want to print out rogue.str, rogue.dex (in the order listed in the class: str, dex, con, int, wis, char)

like image 814
user3205282 Avatar asked Mar 21 '23 21:03

user3205282


1 Answers

I'm not sure if I understood the question, but here is another option. As you said you wanted a generic debug method, I guess you want to print attributes and its values. So a possible way to handle this, would be implementing the __str__(self) method for the class 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

Output:

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:

Note that you must not use Python types as name of variables in other words, don't use str or int as variable names. Call them something else.

like image 168
Christian Tapia Avatar answered Apr 06 '23 09:04

Christian Tapia