翼度科技»论坛 编程开发 python 查看内容

Python教程:类的派生

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
一、派生

派生:子类中新定义的属性的这个过程叫做派生,并且需要记住子类在使用派生的属性时始终以自己的为准
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)


  • 严格以来继承属性查找关系
  • super()会得到一个特殊的对象,该对象就是专门用来访问父类中的属性的(按照继承的关系)
  • super().__init__(不用为self传值)
  • super的完整用法是super(自己的类名,self),在python2中需要写完整,而python3中可以简写为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}
复制代码
来源:https://www.cnblogs.com/xxpythonxx/p/17168779.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具