0

How can I define a python attribute as a class? I want to define a Python class that instantiate the objects that are list type. I can do that using __init__ and a class method, but I'm looking for a way to avoid using a method. Second question is that I'm wondering if I can define a class with a constructor that accept variable arguments (e.g. to use this class to instantiate objects with different No of indexes ([4,5,6] and [1,2,3,4,7]). I've copied my code below. Thanks for your help :)

    class SuperList(list):
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
        def My_list(self):
            return [self.a, self.b, self.c]
    obj1 = SuperList(1, 2, 3)
    List1 = obj1.My_list()
    List1.append(8)
    print(List1)
2
  • How is this different than a regular list? Commented May 26, 2020 at 7:09
  • @Tomerikoo The SuperList class inherits from inbuilt <class 'list> and can be useful for creating custom methods without overwriting inbuilt class. Commented May 26, 2020 at 13:21

2 Answers 2

1

I am not really sure what you are trying to achieve with the "class generated list" but find below one example that may give you a better understanding.

As you are inheriting from list, just by doing the following you would have a custom list implementation:

class SuperList(list):
    def __init__(self, *args):
        super().__init__(args)

list1 = SuperList(1, 2, 3)
list1.append(8)
print(list1)

list2 = SuperList(1, 2, 3, 7, 8, 9)
list2.append(999)
print(list2)
Sign up to request clarification or add additional context in comments.

Comments

0

class SuperList(list):
    def __init__(self,*a):
        self.myList = list(a)
    def My_list(self):
        return self.myList

This works for multiple argument

obj1 = SuperList(1, 2, 54, 3)
print(obj1.My_list())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.