问题遇到的现象和发生背景
为什么eval(repr(s))在这个情况下与原来的s相等(结果为True)
而在这个情况下,r2和r却不相等(结果为False)呢?
问题相关代码,请勿粘贴截图
class Represent(object):
def init(self, x, y):
self.x, self.y = x, y
def repr(self):
return "Represent(x={},y="{}")".format(self.x, self.y)
def str(self):
return "Representing x as {} and y as {}".format(self.x, self.y)
r = Represent(1, "Hopper")
print(r) # prints str
print(r.repr) # prints repr: '<bound method Represent.__repr__ of
Represent(x=1,y="Hopper")>'
rep = r.repr() # sets the execution of repr to a new variable
print(rep) # prints 'Represent(x=1,y="Hopper")'
r2 = eval(rep) # evaluates rep
print(r2) # prints str from new object
print(r2 == r) # prints 'False' because they are different objects
运行结果
print(r2 == r) # prints 'False'