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

后端 未结 5 783
遥遥无期
遥遥无期 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()
    
    0 讨论(0)
  • 2021-01-28 16:22

    You can use super() builtin.

    >>> super(Child, C).A()
    in A
    

    It is usually used to call super class implementation inside subclasses, but it is also allowed outside. Docs state:

    Also note that super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references.

    0 讨论(0)
  • 2021-01-28 16:23

    Call the method on the class explicitly.

    Parent.A(C)
    
    0 讨论(0)
  • 2021-01-28 16:23

    Use a super call passing the type of child class and the desired instance object which is just C:

    super(type(C), C).A() # of the form super(class, obj) where class == Child and obj == C
    
    0 讨论(0)
  • 2021-01-28 16:28

    Having instance C we could get its base class and call its A():
    C.__class__.__base__().A()

    0 讨论(0)
提交回复
热议问题