python:跟踪类中的更改以在最后保存它

2024-04-20 10:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

我从数据库中获取对象,我在多个函数中更改它并将其保存回来。 这很慢,因为它在每次函数调用时都会命中数据库。有没有解构器之类的东西可以保存数据库对象,这样我就不必为每次函数调用保存它,也不必浪费时间。你知道吗


Tags: 对象self数据库dbobjectinitsavedef
2条回答

您可以定义del方法。你知道吗

def __del__(self):
    self.db.save()

但请注意,这违反了数据一致性。你知道吗

不要依赖__del__方法来保存对象。有关详细信息,请参见此blog post。你知道吗

可以通过定义__enter____exit__方法来使用context management protocol

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

然后在创建对象时使用with语句:

with A() as myobj:
    print 'inside with block'
    myobj.do_something()

当您进入with块时,将调用A.__enter__方法。退出with块时,将调用__exit__方法。例如,使用上面的代码,您应该看到以下输出:

enter

inside with block

exit

有关with语句的更多信息:

相关问题 更多 >