ToB企服应用市场:ToB评测及商务社交产业平台

标题: Python教程:类的派生 [打印本页]

作者: 南七星之家    时间: 2023-3-1 17:52
标题: Python教程:类的派生
一、派生

派生:子类中新定义的属性的这个过程叫做派生,并且需要记住子类在使用派生的属性时始终以自己的为准
1 派生方法一(类调用)

指名道姓访问某一个类的函数:该方式与继承无关
  1. class OldboyPeople:
  2.     """由于学生和老师都是人,因此人都有姓名、年龄、性别"""
  3.     school = 'oldboy'
  4.     def __init__(self, name, age, gender):
  5.         self.name = name
  6.         self.age = age
  7.         self.gender = gender
  8. class OldboyStudent(OldboyPeople):
  9.     """由于学生类没有独自的__init__()方法,因此不需要声明继承父类的__init__()方法,会自动继承"""
  10.     def choose_course(self):
  11.         print('%s is choosing course' % self.name)
  12. class OldboyTeacher(OldboyPeople):
  13.     """由于老师类有独自的__init__()方法,因此需要声明继承父类的__init__()"""
  14.     def __init__(self, name, age, gender, level):
  15.         OldboyPeople.__init__(self, name, age, gender)
  16.         self.level = level  # 派生
  17.     def score(self, stu_obj, num):
  18.         print('%s is scoring' % self.name)
  19.         stu_obj.score = num
  20. stu1 = OldboyStudent('tank', 18, 'male')
  21. tea1 = OldboyTeacher('nick', 18, 'male', 10)
复制代码
  1. print(stu1.__dict__)
  2. {'name': 'tank', 'age': 18, 'gender': 'male'}
  3. print(tea1.__dict__)
  4. {'name': 'nick', 'age': 18, 'gender': 'male', 'level': 10}
复制代码
2 派生方法二(super)

  1. class OldboyPeople:
  2.     school = 'oldboy'
  3.     def __init__(self, name, age, sex):
  4.         self.name = name
  5.         self.age = age
  6.         self.sex = sex
  7. #学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
  8. class OldboyStudent(OldboyPeople):
  9.     def __init__(self, name, age, sex, stu_id):
  10.         # OldboyPeople.__init__(self,name,age,sex)
  11.         # super(OldboyStudent, self).__init__(name, age, sex)
  12.         super().__init__(name, age, sex)
  13.         self.stu_id = stu_id
  14.     def choose_course(self):
  15.         print('%s is choosing course' % self.name)
  16. stu1 = OldboyStudent('tank', 19, 'male', 1)
复制代码
  1. print(stu1.__dict__)
  2. {'name': 'tank', 'age': 19, 'sex': 'male', 'stu_id': 1}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4