Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python base class method call: unexpected behavior

Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below?

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: {}
like image 782
stephan Avatar asked Apr 23 '09 07:04

stephan


1 Answers

str(A()) does call __str__, in turn calling dict.__str__().

It is dict.__str__() that returns the value repr(A).

like image 79
codeape Avatar answered Sep 22 '22 23:09

codeape