Python基类方法调用:意外行为
为什么在下面的例子中,Python基类方法调用:意外行为,python,inheritance,dictionary,Python,Inheritance,Dictionary,为什么在下面的例子中,str(A())似乎调用了A.\uuu repr\uuuu(),而不是dict.\uu str\uuu() 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
str(A())
似乎调用了A.\uuu repr\uuuu()
,而不是dict.\uu str\uuu()
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
输出:
call: repr(A) expect: repr(A) get: repr(A)
call: str(A) expect: {} get: repr(A)
call: str(B) expect: {} get: {}
str(A())
确实调用了\uuuuu str\uuuuuu
,反过来调用了dict.\uuuuu str\uuuuu()
返回repr(A)值的是
dict.\uuuu str\uuuu()
。我修改了代码以清除错误:
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)
输出为:
>>> 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 {}
这意味着str函数会自动调用repr函数。因为它是用类A重新定义的,所以它返回“意外”值。我已经发布了一个解决方案。过来看。。。您可能会发现它很有用: 另外,请阅读我介绍这个问题的原始帖子。。。有一个问题是,意外的行为让你大吃一惊