【问题标题】:why is print(eval(repr(instance))) calling the str function and not repr function?为什么 print(eval(repr(instance))) 调用 str 函数而不是 repr 函数?
【发布时间】:2021-05-19 19:24:14
【问题描述】:

在下面的代码块中,为什么语句 print(new) 调用 str 函数而不调用 repr 函数。是因为调用了打印函数吗?

class Robot:

    def __init__(self, name, build_year):
        self.name = name
        self.build_year = build_year

    def __repr__(self):
    return "Robot('" + self.name + "', " + str(self.build_year) + ")"

    def __str__(self):
    return "Name: " + self.name + ", Build Year: " + str(self.build_year)


if __name__ == "__main__":
    x = Robot("Marvin", 1979)


print(str(x))
print(x)
print(repr(x))
new = eval(repr(x))
print(new)


answer is 
Name: Marvin, Build Year: 1979
Name: Marvin, Build Year: 1979
Robot('Marvin', 1979)
Name: Marvin, Build Year: 1979

【问题讨论】:

  • 你知道eval是做什么的吗?
  • 因为这是 print 函数将尝试使用的内容
  • 因为new=eval(repr(x))等价于new=Robot('Marvin', 1979),即它生成一个新对象,然后调用其str()函数。
  • @tif 谢谢 tif 。这是一个完美的答案!
  • @Mike Scotty。是的

标签: python string repr


【解决方案1】:

docs for print

所有非关键字参数都转换为字符串,如 str() 和 写入流<...>

所以是的,print 调用对象的__str__

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2014-01-20
    • 2018-04-10
    • 2018-01-04
    • 2013-10-20
    • 2015-04-14
    • 2011-10-31
    • 2020-03-28
    • 2016-11-19
    相关资源
    最近更新 更多