Home > Software design >  Unexpected behavior when creating a custom append() method for lists
Unexpected behavior when creating a custom append() method for lists

Time:01-26

I am new to object oriented programming so I do not know much about creating a class, so this is confusing me. I have a class that I have made here:

class lst(list):
    def __init__(self):
        self.x = 10
    def appnd(self, *args):
        if len(args) > 1:
            print("you can only append one item")
            return
        else:
            if len(self) > 5:
                print("lst cannot be longer than 5 items")
            else:
                return self.append(args)

The purpose of this is to be able to create a variable with a = 'lst()' and have a behave as a list except include appnd as an additional method. I believe this has worked partially, but I get an unexpected output to the following code:

a = lst()
for i in range(7):
    a.appnd(i)
    print(a)

Output:

[(0,)]
[(0,), (1,)]
[(0,), (1,), (2,)]
[(0,), (1,), (2,), (3,)]
[(0,), (1,), (2,), (3,), (4,)]
lst cannot be longer than 5 items
[(0,), (1,), (2,), (3,), (4,)]
lst cannot be longer than 5 items
[(0,), (1,), (2,), (3,), (4,)]

This is similar to what I want, but I expected:

[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
lst cannot be longer than 5 items
[0, 1, 2, 3, 4]
lst cannot be longer than 5 items
[0, 1, 2, 3, 4]

Why is it showing tuples in the list? Can someone please explain the issue and how to solve it for this case?

CodePudding user response:

Because that's how the *args syntax works. You get a tuple, even if there is only one item. The fact that you had to say len(args) should have been a clue. So, just do

        return self.append(args[0])

And actually, the return is pointless. list.append returns None.

  •  Tags:  
  • Related