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. > > Many thanks > > Jon > > 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') > def __len__ (self): > return len(self.wrapped) > def __getitem__ (self,k): > return self.wrapped[k] > def __add__(self,other): > return self.wrapped+other > > class myListSub(myList): > classCounter=0 > def __init__ (self,value=[]): > self.instanceCounter=0 > myList.__init__(self,value) > def __add__(self,other): > myListSub.classCounter=myListSub.classCounter+1 > self.instanceCounter=self.instanceCounter+1 > myList.__add__(self,other) > def getCounters (self): > return "classCounter=%s instanceCounter=%s" % > (myListSub.classCounter,self.classCounter)
I'm not sure what you're trying to achieve with the __getattr__ in myList, but the reason your __add__ isn't working is that when "a + [5]" is executed, Python tries to find a __coerce__ attribute (to prove this just put a "print attrib" as the first line of your __getattr__). Your customer __getattr__ returns a default string object of 'attribute not found', when it fails to locate this. Python then attempts to call this string, and as your exception states -- strings aren't callable. That should give you enough information to be going onwith. Also, if you're trying to get use to classes, I would suggest you start off with the 'new-style' classes; those are the ones that derive from object. A quick google for new-style classes will sort you. hth a bit, Jon. -- http://mail.python.org/mailman/listinfo/python-list