class A(object):
def __init__(self):
self.db = create_db_object()
def change_Db_a(self):
self.db.change_something()
self.db.save()
def change_db_b(self):
self.db.change_anotherthing()
self.db.save()
I am getting object from database, I changing it in multiple function and saving it back.
which is slow because it hits database on every function call. is there anything like deconstructor where I can save the database object so that I don’t have to save it for every function call and not waste time.
Don’t rely on the
__del__method for saving your object. For details, see this blog post.You can use use the context management protocol by defining
__enter__and__exit__methods:Then use the
withstatement when you create your object:When you enter the
withblock, theA.__enter__method will be called. When you exit thewithblock the__exit__method will be called. For example, with the code above you should see the following output:Here’s more information on the
withstatement: