【问题标题】:Problems understanding __repr__, doesn't print anything even I've decleared it理解 __repr__ 时出现问题,即使我已将其清除也不会打印任何内容
【发布时间】:2018-06-28 09:09:02
【问题描述】:

所以昨天我尝试在我的代码中使用 reprstr 来打印列表中的对象。这里只是我遇到同样问题的小示例代码。

class Something:
    def __init__(self):
        pass

    def __repr__(self):
        return "I want this out"

    def __str__(self):
        return "this comes out"

def main():

    k = Something()
    k
    print(k)

main()

打印的内容:

这就出来了

进程以退出代码 0 结束

为什么我不能从我的对象中取出 repr,即使我在调用对象时给了它返回行?

【问题讨论】:

  • 您可以inspect who the caller was 并相应地进行调整
  • 你总是可以写 str 来返回 repr..def __str__(self): return self.__repr__()
  • @Magnus 我认为 OP 想要根据调用的方法不同的输出
  • 查看此链接:pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/
  • 带有k 的行本身不会调用repr;只有从 REPL 直接执行的表达式语句才会这样做。

标签: python class object repr


【解决方案1】:

解释器有两种方式运行您的代码。 首先是 REPL 上下文(iPython shell,或 ipdb debug env),在这种情况下,python 解释器会调用 __repr__ 函数,我在下面的 ipython env 中尝试过,它的工作原理如下:

In [1]: class Something(object):
   ...:
   ...:     def __repr__(self):
   ...:         return 'in __repr__'
   ...:

In [2]: k = Something()

In [3]: k
Out[3]: in __repr__

其次,当您通过python xxx.py 启动脚本或项目时,解释器将调用__str__

我想你只是尝试了第二种方法。

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    __repr__()__str__() 用于不同的目的。

    • __repr__'s 目标是明确的
    • __str__'s 目标是 可读

    有一篇很棒的文章on this here

    在您的情况下,您的代码只是引用k,希望这将显示k 的r​​epr 版本。这适用于交互式提示,但不适用于脚本。在脚本中,要查看对象的repr 表示,您必须使用repr() 函数。要查看对象的str() 表示,通常必须使用str() 函数。

    值得注意的是,print() 函数默认显示str 表示,这就是为什么您可以打印它而无需先显式调用str()

    class Something:
        def __init__(self):
            pass
    
        def __repr__(self):
            return "I want this out"
    
        def __str__(self):
            return "this comes out"
    
    def main():
    
        k = Something()
        print("repr:", repr(k))
        print("str:", str(k))
        print("defaults to calling str() if available: ", k)
    
    main()
    
    repr: I want this out
    str: this comes out
    defaults to calling str() if available:  this comes out
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多