-
1
''' 继承: 父类 子类 语法: class 子类(父类): pass 默认的父类:object 目的: 提取公共的代码带父类中,子类使用的话则只需要继承父类 从而提高代码的可读性,将代码变的更加简练。 ''' # 父类 class Person(object): def __init__(self, name, age): self.name = name self.age = age def eat(self): print('去楼下吃饭了') # 子类 class Student(Person): def study(self): print('认真学习知识') class Teacher(Person): def teach(self): print('乖乖上课...') class Employee(Person): def work(self): print('其他工作...') student = Student('葫芦娃', 5) student.eat() student.study()
-
2
''' 子类是否可以继承父类所有的内容? 1. 子类无法继承父类私有的属性或者方法 2. 父类的定义的方法不能满足子类的需求,则子类可以定义跟父类同名方法 (重写,覆盖) 当子类调用的时候默认先调用自己的方法,如果自身没有才会去父类中找... 3. 如果在子类中手动调用父类的方法: A. super(子类名,self).方法名() B. 父类名.方法名(sel) ''' class Person(object): def __init__(self, name, age): self.name = name self.age = age self.__money = 10000 # _Person__money def eat(self): print('去楼下吃饭了') def __test(self): # _Person__test print('------------->test') class Student(Person): # def study(self): # print('认真学习知识') # 在子类中定义同名的方法或者属性 def eat(self): # super(Student, self).eat() print('去食堂吃饭啦...') def show(self): print('姓名:{},年龄:{}'.format(self.name,self.age)) # print('存款金额:{}'.format(self.__money)) # _Student__money def study(self): # self.eat() # super(Student, self).eat() Person.eat(self) print('吃饱啦,要好好去学习了....') stu1 = Student('葫芦娃',5) stu1.study() # stu1.eat() # # stu1.show() # 练习: 定义父类Animal,有属性: name,age 动作是:run(self,km), eat(self,food) ,show() # 定义子类Tiger继承Animal,该类中也有一个方法eat(self), # 如果创建Tiger对象调用eat,则打印内容是什么 # 定义子类Dog继承Animal,添加一个color属性,添加一个seeHouse方法和重写run()方法 # 创建Dog类,分别调用seeHouse和run方法和eat()
继承
最新推荐文章于 2025-04-29 21:28:21 发布