Skip to content
Advertisement

Inheritance in nested class in python

I wanted to know which class method is being executed in example below. Is there a way to call explicitly using class name? Kindly help.

Example:-

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        super().test("foo")
        super().test("boo")

run = C()
run.testing()

Output:-

foo
boo

In order to experiment, I tried calling via class name but received error. I understand that, self is for class objects and therefore, should be called via either super() or reference object but my question is how will I know which method is being called during execution and are there any other way to directly call parent method (From Class A) explicitly from Class C?

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        A.test("foo")
        B.test("boo")

run = C()
run.testing()

Output:-

 A.test("foo")
TypeError: test() missing 1 required positional argument: 'input'

Advertisement

Answer

Additional information about the answer that @Samwise gave to your error message:

Methods are actual functions that has an object bound to them. When you call a function on an instance of a class, python will fill the first parameter of your function for you with the reference to that instance and then it become “method”. But if you call a function on a class itself, python won’t fill the first parameter for you so you have to do it yourself. (This is the reason you got: missing 1 required positional argument: 'input' )

class A:
    def foo(self):
        pass

print(type(A.foo))
print(type(A().foo))

As you can see the first one is “function” , second one is “method”. In the first one, you should fill input (what a bad name) manually.

This is the behavior of descriptors. “Functions” implement descriptor protocols.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement