0
Is there any elegant approach available to provide incremented ID to every new object in python?
I tried this way but it looks messy. def init_fruit(self,fruit): self.fruit = fruit Fruit.parent_id += 1 ## self.id = Fruit.parent_id ## Fruit = type("Fruit",(object,),{ "parent_id": 0, ## "__init__": init_fruit, "__str__": lambda self: "ID: {0}\nIt\'s a {1}".format(self.id,self.fruit) }) obj1 = Fruit("Mango") obj2 = Fruit("Orange") obj3 = Fruit("Banana") print("{}\n\n{}\n\n{}".format(obj3 ,obj2, obj1)) https://code.sololearn.com/cibHmLk49p3J/?ref=app
2 Respostas
+ 3
Using global dictionary!
for i in range(5):
globals()[f"Obj{i}"]=Fruit(f"{i}")
+ 1
Abhay Cool! This works like a charm. Thank you