1

I from the program below I want the instance of B to call the method in A but I have no idea how to type cast the object in order for the object to call the method in A which has the same name in B and so the method in A runs but not the one in B.

class A:
def doSomething(self):
    print("do something in A")

class B(A):
def doSomething(self):
    print('do something in B')

def main():
b = B()
b.doSomething()
(A)b.doSomething() # I want b to call the function in A instead of B

main()
Corn
  • 11
  • 2

1 Answers1

1

If all you want to do is call the super class method doSomething on b, this should suffice:

class A(object):

    def doSomething(self):
        print('Do something in A')


class B(A):

    def doSomething(self):
        print('Do something in B')


b = B()
super(B, b).doSomething()

Which prints:

Do something in A

The idea of "type casting" isn't really applicable in python.

kingkupps
  • 3,284
  • 2
  • 16
  • 28
  • I just started learning python recently but I already have some knowledge about java language. that is why I think if you do something like the above, I would have to typecast. Thank you for the answer, I didn't expect to use super like that – Corn Jan 27 '21 at 03:36
  • No prob! [This question](https://stackoverflow.com/questions/4205130/what-is-duck-typing) (and the answers) might help you understand more of the differences between statically typed languages like Java and dynamic ones like Python and Javascript. Long story short: you don't need to know the type of an object to attempt a method call on that object. – kingkupps Jan 27 '21 at 03:42