Corn
Corn

Reputation: 11

Type cast between custom inherited classes

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()

Upvotes: 1

Views: 284

Answers (1)

kingkupps
kingkupps

Reputation: 3504

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.

Upvotes: 1

Related Questions