简体   繁体   English

Python基类方法调用:意外行为

[英]Python base class method call: unexpected behavior

Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below? 为什么str(A())似乎在下面的例子中调用A.__repr__()而不是dict.__str__()

class A(dict):
    def __repr__(self):
        return 'repr(A)'
    def __str__(self):
        return dict.__str__(self)

class B(dict):
    def __str__(self):
        return dict.__str__(self)

print 'call: repr(A)  expect: repr(A)  get:', repr(A())   # works
print 'call: str(A)   expect: {}       get:', str(A())    # does not work
print 'call: str(B)   expect: {}       get:', str(B())    # works

Output: 输出:

call: repr(A)  expect: repr(A)  get: repr(A)
call: str(A)   expect: {}       get: repr(A)
call: str(B)   expect: {}       get: {}

str(A()) does call __str__ , in turn calling dict.__str__() . str(A())调用__str__ ,然后调用dict.__str__()

It is dict.__str__() that returns the value repr(A). 它是dict.__str__() ,返回值repr(A)。

I have modified the code to clear things out: 我修改了代码以清除问题:

class A(dict):
   def __repr__(self):
      print "repr of A called",
      return 'repr(A)'
   def __str__(self):
      print "str of A called",
      return dict.__str__(self)

class B(dict):
   def __str__(self):
      print "str of B called",
      return dict.__str__(self)

And the output is: 输出是:

>>> print 'call: repr(A)  expect: repr(A)  get:', repr(A())
call: repr(A)  expect: repr(A)  get: repr of A called repr(A)
>>> print 'call: str(A)   expect: {}       get:', str(A())
call: str(A)   expect: {}       get: str of A called repr of A called repr(A)
>>> print 'call: str(B)   expect: {}       get:', str(B())
call: str(B)   expect: {}       get: str of B called {}

Meaning that str function calls the repr function automatically. 这意味着str函数自动调用repr函数。 And since it was redefined with class A, it returns the 'unexpected' value. 由于它是用A类重新定义的,因此它返回'意外'值。

I have posted a workaround solution to it. 我已经发布了一个解决方案。 Check it out ... you might find it useful: http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html 看看吧......你可能会发现它很有用: http//blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html

PS Read the original post where I introduced the issue as well ... There problem is the unexpected behavior that catches you by surprise ... PS阅读原帖,我也介绍了这个问题......问题在于意外的行为让你感到惊讶......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM