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

Time:08-15

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()

CodePudding user response:

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

CodePudding user response:

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()
  • Related