Python面向对象之 - 继承

状况一:  子类彻底继承父类全部的属性和方法, 本身没有一点更改.app

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print("跑步!")

    def eat(self, food):
        print("吃%s!"%food)

class Student(Person):
    pass                         # 用pass占位, 彻底继承父类的一切, 并且不作任何修改.

stu = Student("tom", 18)
print(stu.name, stu.age)
stu.run()
stu.eat("apple")

# 结果:
# tom 18
# 跑步!
# 吃apple!

 

状况二:  子类继承父类的全部属性和方法,  并且本身想要增长新的方法.spa

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print("跑步!")

    def eat(self, food):
        print("吃%s!"%food)

class Student(Person):
    def drink(self):           # 增长父类中没有的新的方法.
     print("喝水!")
stu = Student("tom", 18) print(stu.name, stu.age) stu.run() stu.eat("apple")
stu.drink()
# 结果: # tom 18 # 跑步! # 吃apple!
# 喝水!

 

状况三:  子类继承自父类,  可是本身想要彻底替换掉父类中的某个方法.code

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print("跑步!")

    def eat(self, food):
        print("吃%!"%food)

class Student(Person):
    def eat(self):           # 重写父类方法, 将会彻底覆盖掉原来的父类方法.
     print("吃东西!")
stu = Student("tom", 18) print(stu.name, stu.age) stu.run() stu.eat() # 结果: # tom 18 # 跑步! # 吃东西!

 

状况四:  子类继承父类的全部属性和方法,  而且想在原有父类的属性和方法的基础上作扩展.blog

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print("跑步!")

    def eat(self, food):
        print("吃%s!"%food)

class Student(Person):
    def __init__(self, name, age, height):
        super(Student, self).__init__(name, age)       # 对父类属性进行扩展
        self.height = height                           # super()内的(子类名, self)参数能够不写

    def eat(self, food):
        super(Student, self).eat(food)                 # 对父类方法进行扩展
        print("再吃一个!")                              # super()内的(子类名, self)参数能够不写

stu = Student("tom", 18, 175)
print(stu.name, stu.age, stu.height)
stu.run()
stu.eat("apple")
# 结果:# tom  18  175# 跑步!# 吃apple!# 再吃一个!
相关文章
相关标签/搜索