user12074577
user12074577

Reputation: 1419

how to return length of a list from a class in python

So I get this error when I try to get the len() of my list from my class: TypeError: object of type 'Stuff' has no len() when I try:

>>> s = Stuff()
>>> len(s)
error instead of showing 0 like:
>>> l = []
>>> len(l)
0

Code:

class Stuff():
    def __init__(self):
        self.lst = []

Upvotes: 2

Views: 7634

Answers (3)

Hugoagogo
Hugoagogo

Reputation: 1646

Use the __len__ special method

class Stuff(object):
    def __init__(self):
        self.bits = []
    def __len__(self):
        return len(self.bits)

I highly recommend reading through the docs page on special methods. http://docs.python.org/2/reference/datamodel.html#special-method-names

There are a fair number of neat things you can do, such as defining how methods such as

Stuff() += 3 or Stuff()[4] behaves.

Upvotes: 1

Kyle Strand
Kyle Strand

Reputation: 16509

The argument to len can be "a sequence (string, tuple or list) or a mapping (dictionary)": http://docs.python.org/2/library/functions.html#len

It cannot simply be an object, unless that object explicitly defines a __len__ method. This is the method that implicitly gets called by the len function.

Upvotes: 0

Volatility
Volatility

Reputation: 32310

Define the __len__ special method like so:

class Stuff():
    def __init__(self):
         self.lst = []
    def __len__(self):
         return len(self.lst)

Now you can call it like this:

>>> s = Stuff()
>>> len(s)
0

Upvotes: 6

Related Questions