I have a parent class that has a bunch of class methods:
class Parent():
@classmethod
def methodA(cls):
pass
@classmethod
def methodB(cls):
pass
In my subclass, I would like to wrap a subset of the methods inside a "with". It should achieve this effect:
class Child(Parent):
@classmethod
def methodA(cls):
with db.transaction:
super(Child, cls).methodA()
I have a bunch of methods that follow this pattern and would prefer not to repeat myself. Is there a cleaner way to do this?
It seems you should move the with db.transaction into the base. Make a method in the base, returning the db.transaction
@staticmethod
def gettransaction(): return db.transaction
then you overload it in the children as/if needed.
In the base you then do
def methodB(cls):
with cls.gettransaction():
bla ...
Here's a complete working example with a dummy transaction
class transact:
def __enter__(a):
print "enter"
def __exit__(a,b,c,d):
print "exit"
class transact2:
def __enter__(a):
print "enter2"
def __exit__(a,b,c,d):
print "exit2"
class Parent():
@staticmethod
def gettrans():
return transact()
def methodA(cl):
with cl.gettrans():
print "A"
class Child(Parent):
pass
@staticmethod
def gettrans():
return transact2()
p=Parent()
p.methodA()
c=Child()
c.methodA()
this results in
enter
A
exit
enter2
A
exit2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With