Python: how to return the length of the list passed to class as an argument with __len__()

Question:

In the following code the class gets a list as an argument. Object has a "length" variable (length of that list)

The __ len __() method must return the value of "length"

class Gen:
    def __init__(self, lst, length ):
        self.lst = lst  # list
        self.length = length

    def show(self):
        print("List:", self.lst)

    def __len__(self):
        # will return 'length's value
        pass

x = Gen([1, 2, 3, 4])
x.show()
Asked By: Ben

||

Answers:

You can access the length of your attribute ‘lst’ by using "self". Also, because length is based on your attribute, you could define it as a property (or not even declare it …) :

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.lst)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4

If you still want to use the length variable, then you can do this :

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list
    self.length = len(lst)

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.length)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4 

Note that when you update the lst, the attribute length is not updated.

If you still want to have a length property (which feel javaey, because in python you use len), then you can do this:

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list

  @property
  def length(self):
    return len(self.lst)

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.length)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4 

Anyway, there are lot of variants for your question.

Answered By: Sami Tahri

I think you want something like this –

class Gen:
    def __init__(self, lst):
        self.lst = lst  # list
        self.length = len(self.lst)

    def show(self):
        print("List:", self.lst)
        print("List Length:", self.length)

    def __len__(self):
        # will return 'length's value
        return self.length;

x = Gen([1, 2, 3, 4])
x.show()
Answered By: Manik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.