473,383 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

AttributeError: ClassA instance has no attribute '__len__'

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?

Thanks in advance

Mack

Jul 18 '05 #1
3 12092
MackS wrote:
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:
In general you are more likely to get helpful responses from this group if you
post the actual code that has the problem and include the actual traceback.
However...
AttributeError: ClassA instance has no attribute '__len__'

Following the traceback,I see that the offending line is

self.x = arg1 + len(self.y) + 1
len calls the object's __len__ method. self.y is bound to something (an
instance of ClassA) that apparently has no __len__ method

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)

In this case self.y is bound to something different i.e., 'y' :an object of type
str, which has a __len__ method:
'y'.__len__()

1

Michael

Jul 18 '05 #2
"MackS" <ma***********@hotmail.com> schrieb im Newsbeitrag
news:11**********************@f14g2000cwb.googlegr oups.com...
| 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
|
Jul 18 '05 #3
The most simple way to get this error I can think of is like this. It
happens because len does not know how to calculate the lenght of this
object.
-class classA:
- def __init__(self):
- pass

-a = classA()
-print len (a)

Traceback (most recent call last):
File "./test.py", line 10, in ?
print len (a)
AttributeError: classA instance has no attribute '__len__'

You can fix it by adding a __len__ method:
class classA:
def __init__(self):
pass

def __len__(self):
return 0

a = classA()
print len (a)

See http://docs.python.org/ref/sequence-types.html

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: seth | last post by:
Last week I encountered an AttributeError in my unit tests that I wasn'table to catch with an "except AttributeError" statement. The problem stemmed from a class that raised an error inside...
1
by: frank | last post by:
need help with wxpython. wxpython code is made with boa-constructor when i run the code i get this error message: Traceback (most recent call last): File "wxApp1.py", line 24, in ? main()...
2
by: GrelEns | last post by:
hello, i would like if this behaviour can be obtained from python : trap an attributeError from inside a subclassing dict class... (here is a silly examples to explain my question) class...
0
by: Erlend Fuglum | last post by:
I have tried and tried, but cannot figure out the source of the following error: AttributeError: 'module' object has no attribute 'menyHMTL' __doc__ = 'Attribute not found.' __getitem__ =...
3
by: Frank | last post by:
Hello, how do I do this: classA sub A dim frmA as new frmA frmA.showdialog end sub A sub B some stuff
2
by: rsd | last post by:
Hi, I'm trying get Samsung YH-920 mp3 player to work with Debian GNU/Linux. To do that I need to run http://www.paul.sladen.org/toys/samsung-yh-925/yh-925-db-0.1.py script, the idea behind the...
2
by: johnny | last post by:
I am getting a log error. I am running ActiveState Python 2.4.3. Any help greatly appreciated. Here is my code: file.py --------- def main() setupLogging() blah....
7
by: erikcw | last post by:
Hi, I'm trying to build a SQL string sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid, ag, self.data) It raises this error: AttributeError: 'tuple' object has no...
4
by: Nikhil | last post by:
I have recently written a small module. When I import the module, I always get the error only when I do -- Traceback (most recent call last): File "<stdin>", line 1, in <module>
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.