python中子类调用父类的方法

1子类调用父类构造方法python

class Animal(object):
    def __init__(self):
        print("init Animal class~")

    def run(self):
        print("animal run!")


class Dog(Animal):

    def __init__(self):
        #若子类没有重写构造方法,则会调用父类的。不然python不会自动调用父类构造方法。
#显式的调用父类构造方法的三种方式 #Animal.__init__(self) #super(Dog, self).__init__() super().__init__() print("init Dog class~") def run(self): print("dog run!")

测试Dog().run()运行结果以下函数

init Animal class~
init Dog class~
dog run!

子类实现了本身构造函数,就会调用本身的构造函数,python不会自动调用父类构造函数(与Java不同),既然是继承,辣么就应该在子类的构造函数里面手动调用父类的构造函数。上述有三种方式。测试

 

若将Dog类改成:spa

class Dog(Animal):

    def run(self):
        print("dog run!")

这里Dog用的默认构造函数,测试Dog().run()运行结果以下code

init Animal class~
dog run

子类没有定义本身的构造函数时,会调用父类的构造函数。若是有多个父类呢?blog

class Animal(object):
    def __init__(self):
        print("init Animal class~")

    def run(self):
        print("animal run!")


class Father(object):
    def __init__(self):
        print("init Father class~")


class Dog(Animal,Father):
    def run(self):
        print("dog run!")

测试Dog().run()运行结果以下继承

init Animal class~
dog run!

只会运行Animal的构造函数,若将Father放在第一个父类it

class Dog(Father,Animal):
    def run(self):
        print("dog run!")

测试Dog().run()运行结果以下class

init Father class~
dog run!

子类没有定义本身的构造函数时,只会调用第一个父类的构造函数。object

 

2子类调用父类普通方法

class Animal(object):

    def run(self):
        print("animal run!")


class Bird(Animal):

    def run(self):
        #Animal.run(self)
        #super(Bird, self).run()
        super().run()

测试Bird().run()运行结果以下:

animal run!

能够发现和调用构造方法的方式是同样的。

相关文章
相关标签/搜索