Skip to main content
 首页 » 编程设计

python之打印类中的所有属性

2025年05月04日10mfrbuaa

请不要问我是如何让自己陷入这种境地的。 假设我有一个名为 ccollection 的类。

这个类在运行时有以下属性:

ccollection.a.b.x = 1 
ccollection.a.b.y = 3 
ccollection.a.b.z = 4 
... 
ccollection.a.c = 3 
ccollection.b = 3 

这个类将如上所述动态设置。所以没有办法事先知道类中的属性。

现在我想打印这个类中的所有属性,例如:

ccollection.a.b 应该打印

ccollection.a.b.x = 1 
ccollection.a.b.y = 3 
ccollection.a.b.z = 4 

和 ccollection.a 应该打印

ccollection.a.b.x = 1 
ccollection.a.b.y = 3 
ccollection.a.b.z = 4 
ccollection.a.c = 3 

我想你明白了。每次打印都应开始打印同一级别及以下的所有元素。我正在寻找一种递归遍历所有属性的方法(这是一个树状数据结构)

请您参考如下方法:

这种情况确实需要重构。您正在使用未设计为容器的对象。相反,使用一个容器,例如字典或继承自字典的类。


如果您必须使用当前设置,我同意 Blckknght最有前途的方法似乎是使用 dir。

class CCollection(object): 
  def get_children_strings(self): 
    list_of_strings = [] 
    for attr_name in dir(self): 
      if attr_name not in dir(CCollection()): 
        attr = getattr(self, attr_name) 
        if hasattr(attr, 'get_children_strings'): 
          list_of_strings.extend(["." + attr_name + child_string for child_string in attr.get_children_strings()]) 
        else: 
          list_of_strings.append("." + attr_name + " = " + str(attr)) 
    return list_of_strings 
 
  def print_tree(self, prefix): 
    print [prefix + s for s in self.get_children_strings()] 

那你可以

m = CCollection() 
m.a = CCollection() 
m.a.b = CCollection() 
m.a.b.x = 1 
m.a.b.y = 2 
m.a.c = 3 
m.d = 4 
 
m.print_tree("m") 
m.a.print_tree("m.a") 
m.a.b.print_tree("m.a.b") 

并获得输出:

>>> m.print_tree("m") 
['m.a.b.x = 1', 'm.a.b.y = 2', 'm.a.c = 3', 'm.d = 4'] 
>>> m.a.print_tree("m.a") 
['m.a.b.x = 1', 'm.a.b.y = 2', 'm.a.c = 3'] 
>>> m.a.b.print_tree("m.a.b") 
['m.a.b.x = 1', 'm.a.b.y = 2'] 

要更进一步,您可能希望使用具有树遍历功能的类。你可以自动生成当前通过 prefix 参数传递给 print_tree 函数的信息,如果你有一个函数来获取父节点,保证没有循环,和一个保存节点名称的类变量。