Is there any elegant approach available to provide incremented ID to every new object in python? | Sololearn: Learn to code for FREE!

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

9/17/2021 1:17:55 PM

Tushar Kumar

4 Answers

New Answer

+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

+1

Well if youre looking for an elegant and best professional practise way of doing this, it would be your original code cos that's how it should be. just make parent ID a class or static member The use of global is not advisable and recommendable in most cases

+1

https://code.sololearn.com/czpT8ndz2KoH/?ref=app