【问题标题】:Print doesn't use ad-hoc __str__() or __repr__() methods [duplicate]打印不使用临时 __str__() 或 __repr__() 方法[重复]
【发布时间】:2014-08-04 05:01:32
【问题描述】:

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

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

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

【问题讨论】:

  • 如果您在问题中包含运行代码的输出将会很有帮助。

标签: python string printing protocols repr


【解决方案1】:

特殊方法总是在 type 上调用;例如,那是类。见Special method lookup

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

这意味着您不能将__str____repr__ 方法添加到实例 并期望它们被使用。

【讨论】:

  • 呃,我不知道,谢谢。
【解决方案2】:
a.__class__.__str__ = self.output
a.__class__.__repr__ = self.output

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

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2019-05-08
    • 2022-08-17
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多