How to call a Parent Class's method from Child Class in Python?

后端 未结 15 2383
無奈伤痛
無奈伤痛 2020-11-22 10:14

When creating a simple object hierarchy in Python, I\'d like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for

相关标签:
15条回答
  • 2020-11-22 10:41

    If you don't know how many arguments you might get, and want to pass them all through to the child as well:

    class Foo(bar)
        def baz(self, arg, *args, **kwargs):
            # ... Do your thing
            return super(Foo, self).baz(arg, *args, **kwargs)
    

    (From: Python - Cleanest way to override __init__ where an optional kwarg must be used after the super() call?)

    0 讨论(0)
  • 2020-11-22 10:44

    I would recommend using CLASS.__bases__ something like this

    class A:
       def __init__(self):
            print "I am Class %s"%self.__class__.__name__
            for parentClass in self.__class__.__bases__:
                  print "   I am inherited from:",parentClass.__name__
                  #parentClass.foo(self) <- call parents function with self as first param
    class B(A):pass
    class C(B):pass
    a,b,c = A(),B(),C()
    
    0 讨论(0)
  • 2020-11-22 10:46

    Python 3 has a different and simpler syntax for calling parent method.

    If Foo class inherits from Bar, then from Bar.__init__ can be invoked from Foo via super().__init__():

    class Foo(Bar):
    
        def __init__(self, *args, **kwargs):
            # invoke Bar.__init__
            super().__init__(*args, **kwargs)
    
    0 讨论(0)
  • 2020-11-22 10:47
    ImmediateParentClass.frotz(self)
    

    will be just fine, whether the immediate parent class defined frotz itself or inherited it. super is only needed for proper support of multiple inheritance (and then it only works if every class uses it properly). In general, AnyClass.whatever is going to look up whatever in AnyClass's ancestors if AnyClass doesn't define/override it, and this holds true for "child class calling parent's method" as for any other occurrence!

    0 讨论(0)
  • 2020-11-22 10:50

    Python also has super as well:

    super(type[, object-or-type])

    Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

    Example:

    class A(object):     # deriving from 'object' declares A as a 'new-style-class'
        def foo(self):
            print "foo"
    
    class B(A):
        def foo(self):
            super(B, self).foo()   # calls 'A.foo()'
    
    myB = B()
    myB.foo()
    
    0 讨论(0)
  • 2020-11-22 10:50

    Here is an example of using super():

    #New-style classes inherit from object, or from another new-style class
    class Dog(object):
    
        name = ''
        moves = []
    
        def __init__(self, name):
            self.name = name
    
        def moves_setup(self):
            self.moves.append('walk')
            self.moves.append('run')
    
        def get_moves(self):
            return self.moves
    
    class Superdog(Dog):
    
        #Let's try to append new fly ability to our Superdog
        def moves_setup(self):
            #Set default moves by calling method of parent class
            super(Superdog, self).moves_setup()
            self.moves.append('fly')
    
    dog = Superdog('Freddy')
    print dog.name # Freddy
    dog.moves_setup()
    print dog.get_moves() # ['walk', 'run', 'fly']. 
    #As you can see our Superdog has all moves defined in the base Dog class
    
    0 讨论(0)
提交回复
热议问题