我在 Python 3.4 中遇到问题,希望得到任何帮助和/或解释:
基本上我有一个类,该类的函数应该返回另一个类的实例,但使用修改后的字符串表示,以便我以后可以 print() 该实例并查看该函数中添加的 Stuff。
我不明白的是,即使我似乎能够更改该实例的str和repr方法, print() 仍将使用原始表示。
这是一个简化的示例,基本上显示了我尝试过的内容:
class A():
def __str__(self):
return('AAA')
class B():
def output(self):
return('BBB')
def run(self):
a = A()
print("if str(a)({}) equals a.__str__()({})...".format(str(a), a.__str__()))
a.__str__ = self.output
a.__repr__ = self.output
print("... why not now? (str(a) = {} while a.__str__() = {}".format(str(a), a.__str__()))
return a
b = B()
a=b.run()
print("print a: {}, str(a): {}, a.__str__(): {}, a.__repr__():{}".format(a, str(a), a.__str__(), a.__repr__()))
有人可以向我解释一下吗?谢谢你们的时间,伙计们!
编辑:忘记输出,对不起:
[xxx@localhost ~]$ python test.py
if str(a)(AAA) equals a.__str__()(AAA)...
... why not now? (str(a) = AAA while a.__str__() = BBB
print a: AAA, str(a): AAA, a.__str__(): BBB, a.__repr__():BBB
编辑:感谢 Martijn Pieters 的解释!
I changed my code to :
class A():
def __init__(self):
self.str = 'AAA'
def __str__(self):
return(self.str)
class B():
def run(self):
a = A()
a.str = 'BBB'
print(a, str(a), a.__str__())
return a
b = B()
a=b.run()
print("print a: {}, str(a): {}, a.__str__(): {}".format(a, str(a), a.__str__()))
我现在得到了我想要的输出:
python test.py
BBB BBB BBB
print a: BBB, str(a): BBB, a.__str__(): BBB