【问题标题】:How do most people do console.log debugging in Python?大多数人如何在 Python 中进行 console.log 调试?
【发布时间】:2016-08-27 21:13:05
【问题描述】:

在 Node.js 中,当我想快速检查某物的值而不是破坏调试器并单步执行时,我会快速添加一个 console.log(foo) 并获得一个漂亮的:

{
   lemmons: "pie",
   number: 9,
   fetch: function(){..}
   elements: {
      fire: 99.9
   }
}

很清楚!在 Python 中,我得到了这个:

class LinkedList:
  head = None
  tail = None
  lemmons = 99

<__main__.LinkedList instance at 0x105989f80>vars(),

{}

dir()

['_LinkedList__Node', '__doc__', '__module__', 'append', 'get_tail', 'head', 'lemmons', 'remove', 'tail']

呸!看看那些废话——我认为 python 应该是快速、美丽和干净的?这真的是人们的做法吗?他们是否为所有内容实现了客户 str 和自定义 repr?因为这似乎也有点疯狂..

【问题讨论】:

  • 你说 Python 的日志记录很丑?你试过调试 C++ 吗? :)
  • 实例变量进入__init__,不在类级别。这就是为什么你从vars 得到如此无用的输出。
  • 不过,我建议您编写一个自定义 __repr__
  • @user2357112 哇,是的.. 这很有意义。谢谢!
  • 我只是打印那些我感兴趣的属性,像 node.js 那样输出绝对所有东西似乎都太混乱了。

标签: python class debugging object tostring


【解决方案1】:

您可以通过多种不同的方式打印您的对象和 Python 类,这里有一个简单的方式:

class LinkedList:
    head = None
    tail = None
    lemmons = 99

    def __str__(self):
        return str(vars(LinkedList))

print LinkedList()

我建议您从熟悉 str and repr 运算符开始。无论如何,这是一个小例子,使用 python 有很多方法可以漂亮地打印对象和类

【讨论】:

    【解决方案2】:

    期望您implement your own __str__ method 以便您可以选择登录诊断的重要内容。

    但是,可以选择使用几行代码以“漂亮”格式记录整个对象字典。例如:

    from pprint import pformat
    
    class A(object):
        def __init__(self):
            self.foo = 1
            self.bar = {"hello": "world"}
            self._private = 0
    
    a = A()
    print pformat(vars(a))
    # You can also pass pformat to your logger if that's what you have.
    

    这将返回类似这样的内容(取决于您拥有多少数据和width 约束):

    {'_private': 0,
     'bar': {'hello': 'world'},
     'foo': 1}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      相关资源
      最近更新 更多