zoukankan      html  css  js  c++  java
  • 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!

    # 再吃一个!
  • 相关阅读:
    Mac安装Git以及Git和Github使用教程
    JMeter 聚合报告之 90% Line 参数说明
    [loj3525]喷泉公园
    dapr微服务
    Online SQL interpreter
    C# Math.Round()的银行家算法
    使用Visual Studio分析dump
    Qt高级——QTestLib单元测试框架
    深度学习:Keras入门(一)之基础篇
    前端使用a标签启动本地.exe程序
  • 原文地址:https://www.cnblogs.com/chenbin93/p/9049095.html
Copyright © 2011-2022 走看看