newbie class-building question
Peter Otten
__peter__ at web.de
Thu Nov 9 08:29:44 EST 2006
jrpfinch wrote:
> I am constructing a simple class to make sure I understand how classes
> work in Python (see below this paragraph).
>
> It works as expected, except the __add__ redefinition. I get the
> following in the Python interpreter:
>
>>>> a=myListSub()
>>>> a
> []
>>>> a+[5]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: 'str' object is not callable
>>>>
>
> Please could you let me know where I am going wrong. I have hacked
> around with the code and tried googling this error message but am
> having difficulty finding the source of the problem.
> class myList:
> def __init__ (self,value=[]):
> self.wrapped=[]
> for x in value :
> self.wrapped.append(x)
> def __repr__ (self):
> return `self.wrapped`
> def __getattr__ (self,attrib):
> return getattr(self.wrapped,attrib,'attribute not found')
When Python is looking for an attribute that neither exists in myList nor
the 'wrapped' list, you give back a string.
In your case this happens for the __coerce__() method, and the interpreter
ends up calling "attribute not found" which of course must fail. The
solution:
- Don't provide a bogus default for getattr(), and get a traceback that is
easier to understand.
- Use new-style classes (i.e. class myList(object): ...) which look for
special methods in the class, not the instance.
Peter
More information about the Python-list
mailing list