"MackS" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] | I'm new to Python. In general I manage to understand what is happening | when things go wrong. However, the small program I am writing now fails | with the following message: | | AttributeError: ClassA instance has no attribute '__len__' | | Following the traceback,I see that the offending line is | | self.x = arg1 + len(self.y) + 1 | | Why should this call to the built-in len() fail? In a small test | program it works with no problems: | | class foo: | def __init__(self): | self.x = 0 | self.y = 'y' | | def fun(self, arg1): | self.x = arg1 + len(self.y) + 1 | | >>> a = foo() | >>> a.fun(2) | >>> | | No problems; can you help me make some sense of what is happening?
In your program, self.y is an instance of ClassA. The traceback tells you that ClassA has no __len__ attribute (i.e. it is an object that has no no "special" method called __len__, which is what gets called when you do len(obj). In your test program, self.y is "y", a string, which has a __len__ method by design: (see dir("y"), which gives you: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] If you want len(self.y) to work, self.y must be an object that implements a __len__ method. In other words, your "ClassA" needs a __len__ method. A trivial example: class ClassA: def __init__(self, text): self.text = text def __len__(self): #return something useful return len(self.text) y = ClassA("Hello") print len(y) # prints 5 Regards, -- Vincent Wehren | | Thanks in advance | | Mack | -- http://mail.python.org/mailman/listinfo/python-list