【问题标题】:python: printing __dict__ : is it possible to print in the same order as what's listed in the class?python: 打印 __dict__ : 是否可以按照与类中列出的顺序相同的顺序打印?
【发布时间】:2014-01-20 02:15:46
【问题描述】:

抱歉,可能是个愚蠢的问题,但找不到答案。上下文是我是 python 新手,做一个简单的 rpg。类将具有一些基本的 rpg 属性,例如

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

由于我将根据字符类分配值,因此我想创建一个通用的调试方法,以便稍后为给定的类打印这些值。我的问题是:有没有一种简单的方法可以稍后按顺序打印出来(str,dex,con ...)。

我要带基本款了

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

现在以特定的顺序打印出来 敏捷:2, 诠释:4, 字符:6, 智慧:5, 字符串:1, 缺点:3

但如果我忽略了一些东西以保持秩序,我会喜欢帮助/建议

*编辑:为了澄清我是否制作了 rogue = Character(1,2,3,4,5,6),我想打印出 rogue.str、rogue.dex(按类中列出的顺序:str , dex, con, int, wis, char)

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    我不确定我是否理解了这个问题,但这是另一种选择。正如您所说,您想要通用调试方法,我猜您想要打印属性及其值。因此,一种可能的处理方法是为 Character 类实现 __str__(self) 方法

    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
    

    编辑:

    请注意,您不得使用 Python 类型作为变量名,换句话说,不要使用 strint 作为变量名。叫他们别的名字。

    【讨论】:

    • 非常有帮助,谢谢(也感谢关于变量的提示)
    【解决方案2】:

    尝试将订单列成一个列表,然后按该顺序打印出来:

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

    订单可以是['foo', 'bar']...

    您可以为每个类定义顺序,然后使用an.order 代替顺序

    【讨论】:

    • 这不能保证顺序,因为python中的dict对象甚至不保留顺序。
    • @noa:是的,它会,因为它按order 列表的顺序打印,而不是字典的顺序。
    • 我会选择getattr 而不是__dict__,以防您以后想更改属性查找的工作方式。
    • 我明白你在说什么。这很令人困惑,因为您不使用 OP 的值。
    • @noa,这添加了一个要打印的订单。这就是整个 for 循环的事情。顺序必须由程序员定义,而不是 python。
    【解决方案3】:

    Python dict 不保留顺序。所以简短的回答是否定的,你不能按顺序打印你的属性字典。但是,可能会有所帮助,您可以在打印之前对键进行排序:

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

    它将打印:char: 6, con: 3, dex: 2, int: 4, str: 1, wis: 5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多