I wish to have a decorator on a class method using private fields. Consider this:
class MyDB():
def __init__(self, value):
self.value = value
def open_connection(self):
print ("open connection for "+self.value)
def close_connection(self):
print ("close connection "+self.value)
def doA(self, request):
self.open_connection()
print ("DO A "+request)
self.close_connection()
def doB(self):
self.open_connection()
print ("DO B")
self.close_connection()
and
db = MyDB('remote')
db.doA(request='ABC')
will result in:
open connection for remote
DO A ABC
close connection remote
So far so good but you will note the open/close on each method is redundant. What I wish to do is add a wrapper such that:
def make_connection(func):
def wrapper(*args, **kwargs):
#self.open_connection() <--this is what I need but how?
r = func(*args, **kwargs)
#self.close_connection() <--this is what I need but how?
return r
return wrapper
and later I can simply do
@make_connection
def doA(self, request):
print ("DO A "+request)
@make_connection
def doB(self):
print ("DO B")
What's the problem?
I couldnt figure how to use the self in the make_connection wrapper. After all, when creating a connection, I need to use self.open_connection and self.close_connection() (in this dummy example it has value and in the real problem theres much of business going on). I used this reference from SO but couldnt integrate it in my dummy example.
How can I integrate self in a wrapper?