1

How to write a class that makes an list for each instance. I am concerned on the class part. I know how to make a int , double or string, but I need an list (string).

The list will have later values assigned to it, when it is an instance and there will be custom methods in the class for the objects/instances.

2
  • Just add a variable self.my_list = [] or my_list = lsit() in your __init__() method? Commented Mar 11, 2018 at 6:10
  • The second way should be self.my_list = list() of course. I obviously failed my proof reading. ;-) Commented Mar 11, 2018 at 7:06

1 Answer 1

1

Classes in Python can have their member variables instantiated within the __init__ function, which is called upon creation of the class object. You should read up on classes here if you are unfamiliar with how to create one. Here is an example class that instantiates a list as a member and allows appending to the list:

   class ListContainer:
       def __init__(self):
          self.internal_list = [] # list member variable, unique to each instantiated class
       def append(elem):
          self.internal_list.append(elem)
       def getList():
          return self.internal_list

  list_container_1 = ListContainer()
  list_container_1.append('example')
  print list_container_1.getList() # prints ['example']
  list_container_2 = ListContainer()
  print list_container_2.getList() # prints []
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.