【发布时间】: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。是的