can I call operator overloader in superclass?

Emile van Sebille emile at fenx.com
Thu Jun 20 15:17:58 CEST 2002


Jon J. Morin
> classAListSub(AList):
>         repr_calls = 0
>         def __init__(self, list=[]):
>                 AList.__init__(self, list)
>         def __repr__(self):
>                 AListSub.repr_calls = AListSub.repr_calls + 1
>                 print "Calling __repr__ in superclass"
>                 AList.__repr__(self)
>                 print "Method called %d times." %
(AListSub.repr_calls)
> ...
> ...
> ...
> I can create instances on AListSub by passing in a string, or a list
as in
> >>> x = AListSub('sasquatch')
> >>> x
> Calling __repr__ in superclass
> Method called 1 times.
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> TypeError: repr not string
>
> For one, I don't understand the error.  For seconds, can I call
__repr__ in
> the superclass from __repr__ in the subclass?

You should return a string from the __repr__ method:

>>> class test:
...     def __repr__(self):
...             print 'in __repr__'
...
>>> t = test()
>>> `t`
in __repr__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __repr__ returned non-string (type None)
>>> class test:
...     def __repr__(self):
...             print 'in __repr__'
...             return "string"
...
>>> t = test()
>>> `t`
in __repr__
'string'
>>>

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list