How do I create lists in classes in Python?

I want to operate a local list in a class in Python. I can not do that:

class cCompetition:
    lcPersonAll = []

    def AddPerson(self, cPersonNew):
        lcPersonAll.append(cPersonNew)

cCompetition1 = cCompetition()
cCompetition1.AddPerson("Smith")

However, global list is possible.

Comments

  • Let us see what you have tried and the error you are getting

  • You can subclass list like this

    class SMS_store(list):
    
        def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
            self.append((False, from_number, time_arrived, text_of_SMS))    #append tuple to self
    
        def message_count(self):
            return len(self)
    

    Notice there is no need for init unless you wish to do something extra there.

    You don't need to append a list and then turn it into a tuple, you can create the tuple directly with () instead of []
    Learn Python https://hackr.io/tutorials/learn-python

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories