Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected behavior when creating a custom append() method for lists

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading