【发布时间】:2013-03-13 17:19:36
【问题描述】:
我正在使用一些需要连接到数据库的类。只有在执行实际操作时才真正需要连接。我想延迟连接阶段,直到真正需要它。为此,我想做类似的事情:
class MyClass
def __init__(self):
self.conn = None
def connect(self):
if self.conn : return
self.conn = ConnectToDatabase()
@connect
def do_something1(self):
self.conn.do_something1()
@connect
def do_something2(self):
self.conn.do_something2()
但我不知道如何为类定义 connect 装饰器。
我当然可以这样做:
def do_something1(self):
self.connect()
self.conn.do_something1()
但使用装饰器似乎是一种更易读的解决方案。有可能吗?
【问题讨论】:
标签: python decorator lazy-initialization