0

So I have a class called Info, which takes as input a name an address and a country. My plan is to create an object and put it inside an array (I think I already know how to do this part), but how do I make it so that I automatically create an ID for each object that I create? i.e. Whenever I instantiate an object, an id (starting from 0 and increments by 1) is assigned to it that is unique to that object. One plan that I had is to just put it inside an array, and the object's ID will be its index number. However, when I delete something from, say, index 3, the index after that will now become the new index 3- the id numbers of each object will not be static this way. I also want to be able to delete objects inside the array using that ID number so I need the numbers to be static to the object (e.g. id number does not change). Below is my code:

info_array = []

class Info():

    
    def __init__(self, name, address, country):
        self.name = name
        self.address = address
        self.country = country
        

    def add_entry(self):
        #Appends an object inside an array
        new_name = self.name
        new_address = self.address
        new_country = self.country
        
        info_array.append(Info(new_name,new_address,new_country))

    @staticmethod
    def delete_entry(id):
        # Deletes an object inside an array based on its ID NUMBER (id number = index, for now)
        
        try:
            info_array.pop(id)
            print(f"successfully removed id {id},{info_array[id].name} from the list")
        except:
            pass


test1 = Info("test1","address1","Japan")
test1.add_entry()
test2 = Info("test2","address2","Korea")
test2.add_entry()
    
Info.delete_entry(0)
Axe319
  • 3,673
  • 2
  • 11
  • 28
TheShin
  • 77
  • 4

0 Answers0