Call overridden method of parent class with child class object in python

后端 未结 5 776
遥遥无期
遥遥无期 2021-01-28 15:39

I have came around this question during an interview:

class Parent(object):
    def A(self):
        print \"in A\"
class Child(Parent):
    def A(self):
                


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 16:19

    As you see, methods of objects always have the self parameter.

    You can call objects methods as

    C.A()
    

    or equivalently, by explicitly passing the self parameter, as:

    Child.A(C)
    

    In the second way, you can call also the method of the parent class using the C instance:

    Parent.A(C)
    

    If you are looking for a general method to solve this (i.e. without knowing the name of the parent class), you can use super() and type():

    super(type(C)).A(C)
    

    However, super() has a nice additional argument to specify an object instance, so you could write also:

    super(type(C), C).A()
    

提交回复
热议问题