B
B
Boris192018-04-20 17:04:23
Python
Boris19, 2018-04-20 17:04:23

Use context manager when inheriting?

I have a class and a method:

class Test(object):
    def do(self):
        # do something
        # do something else

And there is a successor of this class
class Test2(Test):
    def do(self):
       # do something other

But at the same time, I need the code # do something else from the do method of the Test class to be executed after the execution of the do class Test2. Can this be done transparently somehow using a decorator or a context manager? so that you can create different descendant classes from the Test class, and when their do method is called, after its execution, the # do something else code is executed.
Can during the initialization of an object of class Test2 somehow dynamically wrap the do method in the context manager from the Test constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2018-04-20
@planc

I didn’t understand anything from such a description of the problem and what side the context managers are here, but maybe you wanted to do this:
after reading it again :)

class Test:
    def do(self, cb=None):
        print("i am test")
        if callable(cb):
            cb()
        print("i am test")


class Test2(Test):
    def do(self):
        super().do(self.mycb)

    def mycb(self):
        print("i am test2")


t = Test2()
t.do()

i am test
i am test2
i am test

or like this:
class Test:
    def do(self):
        print("i am test")
        if hasattr(self, 'mycb'):
            self.mycb()
        print("i am test")


class Test2(Test):

    def mycb(self):
        print("i am test2")


t = Test2()
t.do()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question