Python: the cleanest way to wrap each method in a parent class in "c"

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 the "c". He 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 prefer not to repeat. Is there a cleaner way to do this?

+6
source share
1 answer

It seems you should move from db.transaction to the database. Make a method in the database by returning db.transaction

 @staticmethod def gettransaction(): return db.transaction 

then you overload it in child elements if necessary.

In the base you do

  def methodB(cls): with cls.gettransaction(): bla ... 

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

it leads to

 enter A exit enter2 A exit2 
+3
source

Source: https://habr.com/ru/post/906564/


All Articles