2

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
4

2 に答える 2

2

特別なメソッドは常にtypeで呼び出されます。たとえば、それはクラスです。特別な方法の検索を参照してください。

カスタム クラスの場合、特別なメソッドの暗黙的な呼び出しは、オブジェクトのインスタンス ディクショナリではなく、オブジェクトの型で定義されている場合にのみ正しく動作することが保証されます。

__str__これは、または__repr__メソッドをインスタンスに追加して、それらが使用されることを期待できないことを意味します。

于 2014-06-13T15:14:13.920 に答える