Python-是否有内置功能可以打印对象的所有当前属性和值?

发布于 2021-02-02 23:10:39

所以我在这里寻找的是类似PHP的print_r函数。

这样一来,我可以通过查看问题对象的状态来调试脚本。

关注者
0
被浏览
61
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你要vars()pprint()

    from pprint import pprint
    pprint(vars(your_object))
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你实际上是将两种不同的东西混合在一起。

    使用dir(),vars()inspect模块来得到你所感兴趣的是(我用__builtins__作为一个例子,你可以使用任何对象,而不是)。

    >>> l = dir(__builtins__)
    >>> d = __builtins__.__dict__
    随心所欲地打印该词典:
    
    >>> print l
    ['ArithmeticError', 'AssertionError', 'AttributeError',...
    

    要么

    >>> from pprint import pprint
    >>> pprint(l)
    ['ArithmeticError',
     'AssertionError',
     'AttributeError',
     'BaseException',
     'DeprecationWarning',
    ...
    
    >>> pprint(d, indent=2)
    { 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
      'AssertionError': <type 'exceptions.AssertionError'>,
      'AttributeError': <type 'exceptions.AttributeError'>,
    ...
      '_': [ 'ArithmeticError',
             'AssertionError',
             'AttributeError',
             'BaseException',
             'DeprecationWarning',
    ...
    

    交互式调试器中还可以作为命令提供漂亮的打印:

    (Pdb) pp vars()
    {'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                      'AssertionError': <type 'exceptions.AssertionError'>,
                      'AttributeError': <type 'exceptions.AttributeError'>,
                      'BaseException': <type 'exceptions.BaseException'>,
                      'BufferError': <type 'exceptions.BufferError'>,
                      ...
                      'zip': <built-in function zip>},
     '__file__': 'pass.py',
     '__name__': '__main__'}
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看