从子级调用super方法时,何时使用self,super()和类名?

时间:2019-05-03 03:24:34

标签: python

super().method()ClassName.method()做同样的事情,但是何时使用super().method()self.method()

根据我的理解,当从同一方法调用的超级方法时,将使用super().method(),而从其他方法调用的情况将使用self.method()

class Animal():
    def run(self):
        print('running')

    def walk(self):
        print('walking')


class Cat(Animal):
    def run(self):
        super().run()

    def walk_fast(self):
        self.walk()       ---> super().walk() also works but any reason using one over the other ?

c = Cat()
c.run()
c.walk_fast()

4 个答案:

答案 0 :(得分:0)

super()引用父类,而self.method()执行类本身的方法。

由于Cat继承自Animal,因此c.run()应该打印running

但是,您不必在run()中重新定义Cat函数,因为它已经从Animal继承了方法。 c.run()将已经打印running

类似地,self.walk()在您的函数中起作用,因为它是在Animal中定义的,并且Cat继承自Animal

super()通常与__init__()一起使用,您要在其中初始化子类中父类的属性。请查看this question,了解更多详细信息。

答案 1 :(得分:0)

下面的代码应为您清楚

coqtop -noinit
Welcome to Coq 8.9.0 (April 2019)

Coq < Inductive T := t.
T is defined
T_rect is defined
T_ind is defined
T_rec is defined

Coq < Definition by := t.
by is defined

输出将为

class Animal():
    def run(self):
        print('running')

    def walk(self):
        print('Animal is walking')

    #Static method called walk
    @staticmethod
    def static_walk():
        print('Animal is walking in static')

class Cat(Animal):

    def run(self):
        super().run()

    def walk(self):
        print('Cat is walking')

    def walk_fast(self):
        #This calls walk of Animal
        super().walk()

        #This calls walk of Cat
        self.walk()

        #This calls static method walk of Animal
        Animal.static_walk()
  • running Animal is walking Cat is walking Animal is walking in static Cat().walk_fast()将调用super().walk()类的walk,因此您看到Animal

  • 如果在超类中实现,则执行Animal is walking会调用超类的方法

  • super().method()将调用self.walk()类的walk,因此您看到Cat

  • Cat is walking调用类本身的方法

  • 执行self.method()将调用该类的ClassMethod.method()方法,因此staticsuper().method()是不同的!

  • ClassName.method()将调用Animal.static_walk()类的静态方法,因此您会看到Animal

答案 2 :(得分:0)

使用super()是对父类的引用。它通常与描述符和魔术方法(例如__init__)一起使用。它允许您直接从父类调用方法,而不必定义父类名称。它还允许您在mro

之后移动多个继承级别。

使用self并没有直接区别,除非与方法名称冲突,即

class Animal():
    def run(self):
        print('running')

    def walk_fast(self):
        print('walking')


class Cat(Animal):
    def run(self):
        super().run()

    def walk_fast(self):
        super(Cat).walk_fast()
        print('After walking')

c = Cat()
c.run()
c.walk_fast()

答案 3 :(得分:0)

实际上,名称解释了所有内容,如果您以此方式编写代码,则可以看到不同之处

class Animal:
    def run(self):
        print('running')

    def walk(self):
        print('walking')


class Cat(Animal):
    def run(self):
        # override to make a difference between self.run() and super().run()
        print('running like a cat')

    def run_super(self):
        super().run()

    def run_self(self):
        self.run()


c = Cat()
c.run() # running like a cat
c.run_super() #running
c.run_self() # running like a cat
c.walk() # Cat don't have walk, call go to Animal (e.g. super())