Python面向对象之 - 继承

情况一:  子类完全继承父类所有的属性和方法, 自己没有一点更改.

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!

情况二:  子类继承父类的所有属性和方法,  而且自己想要增加新的方法.

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!
# 喝水!

情况三:  子类继承自父类,  但是自己想要完全替换掉父类中的某个方法.

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 # 跑步! # 吃东西!

情况四:  子类继承父类的所有属性和方法,  并且想在原有父类的属性和方法的基础上做扩展.

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!

# 再吃一个!

猜你喜欢

转载自www.cnblogs.com/chenbin93/p/9049095.html