I have a recursive function. My base case is:

somemethod(somelist)
[INDENT]if len(somelist) == 0[/INDENT]
[INDENT][INDENT]return[/INDENT][/INDENT]
...

This is suppose to return the function to the place where it was called from.

main()
...
somemethod(somelist)
...

But I get this error:

AttributeError: Trie instance has no attribute '__len__'

This is what I print out:

Somemethod called..
length: 1
Somemethod called..
length: 1
Somemethod called..
length: 2
Somemethod called..
length: 1
Somemethod called..
length: 1
Somemethod called..
length: 0
I'm trying to return... I found error! -- this is the base case!
Somemethod called..
length:

length is the len of the list.
Can someone kindly help me out!

Thanks

drjay

Recommended Answers

All 2 Replies

Each nesting has to be self contained. It should pass (fall out) of the nesting with an error.

bool DoMyTask(    .... )
{

...

            if (!DoMyTask( ... ))
                  return false;

....
    return true;
}

AttributeError: Trie instance has no attribute '__len__'

This indicates that the object you have passed to your recursive method is not a built-in datatype. I'm guessing it's a class that you wrote called Trie.

In order to use the built-in len() function on a user-defined object, you must overload the __len__ function of that class.

Let me demonstrate:

>>> class myClass(object):
...     def __init__(self, param):
...         self.param = param
...     def __len__(self):
...         return len(self.param)
...     
>>> mc = myClass('Test')
>>> len(mc)
4
>>> mc = myClass([1,2,3,4,5,6,7,8,9])
>>> len(mc)
9
>>>

So basically, you need to define what the len() function should be getting the length of. In this case I want it to tell me the length of the param member.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.