2

我在 Python 3.4 中遇到问题,希望得到任何帮助和/或解释:

基本上我有一个类,该类的函数应该返回另一个类的实例,但使用修改后的字符串表示,以便我以后可以 print() 该实例并查看该函数中添加的 Stuff。

我不明白的是,即使我似乎能够更改该实例的strrepr方法, 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
4

2 回答 2

2

总是在类型上调用特殊方法;例如,那是类。请参阅特殊方法查找

对于自定义类,特殊方法的隐式调用只有在对象类型上定义时才能保证正常工作,而不是在对象的实例字典中。

这意味着您不能向实例__str__添加或__repr__方法并期望使用这些方法。

于 2014-06-13T15:14:13.920 回答
0
a.__class__.__str__ = self.output
a.__class__.__repr__ = self.output

但在 Python2.7 中,您的原始代码可以正常工作。唔。

于 2014-06-13T15:35:48.670 回答