python : tracking change in class to save it at the end -


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 getting object database, changing in multiple function , saving back. slow because hits database on every function call. there deconstructor can save database object don't have save every function call , not waste time.

don't rely on __del__ method saving object. details, see blog post.

you can use use context management protocol defining __enter__ , __exit__ methods:

class a(object):     def __enter__(self):         print 'enter'         # create database object here (or in __init__)         pass      def __exit__(self, exc_type, exc_val, exc_tb):         print 'exit'         # save database object here      # other methods 

then use with statement when create object:

with a() myobj:     print 'inside block'     myobj.do_something() 

when enter with block, a.__enter__ method called. when exit with block __exit__ method called. example, code above should see following output:

enter

inside block

exit

here's more information on with statement:


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -