Home > Back-end >  Why I can't use parent's function in parent's class when using override in child'
Why I can't use parent's function in parent's class when using override in child'

Time:07-19

I have two classes:

class A():
    def __init__(self):
        pass

    def func_1(self,a,b):
        #do some stuff
    
    def other_func(self,a,b):
        if b:
            self.func_1(a,b)
        else:
            #do other stuff



class B(A):
    def __init__(self):
        A.__init__(self)
    
    def func_1(self):
        for i in range(10):
            super().func_1(i,i 1)

When I do this:

b = B()
b.other_func(5,5)

I get this error:

TypeError: func_1() takes 1 positional argument but 3 were given

Why is this and how should this be done? I thought that when calling other_func I would be using func_1 from A and not the override one from B

CodePudding user response:

The error occurs because self is an instance of B, so self.func_1(...) is equivalent to B.func_1(self, ...).

As for how to fix it, it depends on what func_1 actually does, and what its actual name is for that matter. You could possibly:

  1. Rename one of them
  2. Make a private or class-private copy of A.func_1
    1. Or, if it's not actually used publicly, rename it so that it's private or class-private itself
  3. Use A.func_1(self, a, b) in A.other_func, but that'd prevent other child classes from properly overriding func_1, so I don't recommend it. I don't think it has any advantages over using a class-private copy.
  • Related