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 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:
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 the with
statement when you create your object:
with A() as myobj:
print 'inside with block'
myobj.do_something()
When you enter the with
block, the A.__enter__
method will be called. When you exit the with
block the __exit__
method will be called. For example, with the code above you should see the following output:
enter
inside with block
exit
Here's more information on the with
statement:
- Understanding Python's "with" statement
You can define a del method.
def __del__(self):
self.db.save()
But note that this violates data consistency.
精彩评论