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!

    # 再吃一个!
  • 相关阅读:
    个人冲刺二(7)
    个人冲刺二(6)
    个人冲刺二(5)
    个人冲刺二(4)
    对称二叉树 · symmetric binary tree
    108 Convert Sorted Array to Binary Search Tree数组变成高度平衡的二叉树
    530.Minimum Absolute Difference in BST 二叉搜索树中的最小差的绝对值
    pp 集成工程师 mism师兄问一问
    17. Merge Two Binary Trees 融合二叉树
    270. Closest Binary Search Tree Value 二叉搜索树中,距离目标值最近的节点
  • 原文地址:https://www.cnblogs.com/chenbin93/p/9049095.html
Copyright © 2011-2022 走看看