<分区> 分区>
我在 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
