Search code examples
pythoninheritancesuper

How to only execute partial codes of a method of super class in python?


I know how to call the method of super class by using super(), like these:

>>> class A:
>>>     def func1(self):
>>>         print("1")
>>>         print("2")
>>>         print("3")

>>> class B(A):
>>>     def func1(self):
>>>         super().func1()
>>>         print("4")

>>> b = B()
>>> b.func1()
1
2
3
4

But now I would like to only execute partial codes of A.func1() in b.func1() and make the result looks like:

1
3
4

Are there any built-in function or site-package can help me to do that?


Solution

  • You need to add some code in A.func1() to suppress print(2)

    class A:
        def func1(self):
            print(1)
            if type(self) is A:
                print(2)
            print(3)
    
    class B(A):
        def func1(self):
            super().func1()
            print(4)
    
    A().func1()
    print()
    B().func1()
    

    Output:

    1
    2
    3
    
    1
    3
    4