【发布时间】:2014-08-04 05:01:32
【问题描述】:
我在 Python 3.4 中遇到问题,希望得到任何帮助和/或解释:
基本上我有一个类,它的函数应该返回另一个类的实例,但使用修改后的字符串表示,以便我以后可以 print() 该实例并查看该函数中添加的东西。
我不明白的是,即使我似乎能够更改该实例的 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
【问题讨论】:
-
如果您在问题中包含运行代码的输出将会很有帮助。
标签: python string printing protocols repr