Python + class .__ dict__。你能隐藏一个属性吗?

时间:2017-02-01 20:27:50

标签: python

快速提问。我有一个有大约20个属性的类,其中一个是列表列表(存储一些时间序列数据)。我发现.__ dict __非常方便调试,但输出对列表列表变得非常讨厌......有没有办法设置.__字典__显示/隐藏什么?

class MyClass(object):

def __init__(self, whoami):
    self.whoami = whoami

    self.attribute1= ''
    self.attribute2= 0
    self.attribute3= 0  
    self.attribute4= 2
    self.attribute5= 'stuff'
    self.attribute6= 0

    self.data = []  #my list of lists... 

1 个答案:

答案 0 :(得分:2)

一种解决方案可能是使用pprint.pprint并使用depth参数:

In [4]: class MyClass(object):
   ...:
   ...:     def __init__(self, whoami):
   ...:         self.whoami = whoami
   ...:
   ...:         self.attribute1= ''
   ...:         self.attribute2= 0
   ...:         self.attribute3= 0
   ...:         self.attribute4= 2
   ...:         self.attribute5= 'stuff'
   ...:         self.attribute6= 0
   ...:
   ...:         self.data = [[1,2,3, [4,5,6,[7,8,9], [3,4]]], 'a','b','c',['d','e',['f']]]
   ...:

In [5]: obj = MyClass(42)

In [6]: print(obj.__dict__)
{'attribute1': '', 'whoami': 42, 'attribute5': 'stuff', 'attribute2': 0, 'attribute4': 2, 'data': [[1, 2, 3, [4, 5, 6, [7, 8, 9], [3, 4]]], 'a', 'b', 'c', ['d', 'e', ['f']]], 'attribute6': 0, 'attribute3': 0}

现在,您可以在调试时调整深度参数以获得更清晰的外观:

In [7]: from pprint import pprint

In [8]: print(pprint.__doc__)
Pretty-print a Python object to a stream [default is sys.stdout].

In [9]: pprint(obj.__dict__)
{'attribute1': '',
 'attribute2': 0,
 'attribute3': 0,
 'attribute4': 2,
 'attribute5': 'stuff',
 'attribute6': 0,
 'data': [[1, 2, 3, [4, 5, 6, [7, 8, 9], [3, 4]]],
          'a',
          'b',
          'c',
          ['d', 'e', ['f']]],
 'whoami': 42}

In [10]: pprint(obj.__dict__, depth=2)
{'attribute1': '',
 'attribute2': 0,
 'attribute3': 0,
 'attribute4': 2,
 'attribute5': 'stuff',
 'attribute6': 0,
 'data': [[...], 'a', 'b', 'c', [...]],
 'whoami': 42}

In [11]: pprint(obj.__dict__, depth=1)
{'attribute1': '',
 'attribute2': 0,
 'attribute3': 0,
 'attribute4': 2,
 'attribute5': 'stuff',
 'attribute6': 0,
 'data': [...],
 'whoami': 42}