zoukankan      html  css  js  c++  java
  • 类的派生

    类的派生

    一、派生

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

    1.1 派生方法一(类调用)

    • 指名道姓(类名点方法)访问某一个类的函数:该方式与继承无关
    class People:
        """由于学生和老师都是人,因此人都有姓名、年龄、性别"""
        school = 'hnnu'
    
        def __init__(self, name, age, gender):
            self.name = name
            self.age = age
            self.gender = gender
    
    
    class Student(People):
        """由于学生类没有独自的__init__()方法,因此不需要声明继承父类的__init__()方法,会自动继承"""
    
        def choose_course(self):
            print('%s is choosing course' % self.name)
    
    
    class HnnuTeacher(People):
        """由于老师类有独自的__init__()方法,因此需要声明继承父类的__init__()"""
    
        def __init__(self, name, age, gender, level):
            People.__init__(self, name, age, gender)
            self.level = level  # 派生
    
        def score(self, stu_obj, num):
            print('%s is scoring' % self.name)
            stu_obj.score = num
    
    
    
    
    stu1 = Student('laowang', 18, 'male')
    tea1 = HnnuTeacher('randy', 18, 'male', 10)
    print(stu1.__dict__)
    {'name': 'laowang', 'age': 18, 'gender': 'male'}
    print(tea1.__dict__)
    {'name': 'randy', 'age': 18, 'gender': 'male', 'level': 10}
    

    1.2 派生方法二(super)

    • 严格以来继承属性查找关系
    • super()会得到一个特殊的对象,该对象就是专门用来访问父类中的属性的(按照继承的关系)
    • super().__init__(不用为self传值)
    • super的完整用法是super(自己的类名,self),在python2中需要写完整,而python3中可以简写为super()
    class People:
        school = 'hnnu'
    
        def __init__(self, name, age, sex):
            self.name = name
            self.age = age
            self.sex = sex
    
    
    class Student(People):
        def __init__(self, name, age, sex, stu_id):
            # People.__init__(self,name,age,sex)
            # super(People, self).__init__(name, age, sex)
            super().__init__(name, age, sex)
            self.stu_id = stu_id
    
        def choose_course(self):
            print('%s is choosing course' % self.name)
    
    
    stu1 = Student('laowang', 19, 'male', 1)
    print(stu1.__dict__)
    {'name': 'laowang', 'age': 19, 'sex': 'male', 'stu_id': 1}
    
    在当下的阶段,必将由程序员来主导,甚至比以往更甚。
  • 相关阅读:
    读取组合单元格
    Spire.XLS:一款Excel处理神器
    linq
    LINQ语句中的.AsEnumerable() 和 .AsQueryable()的区别
    合并单元格
    web sec / ssd / sshd
    linux——cat之查看cpu信息、显示终端、校验内存.............
    MATLAB mcr lib的环境变量书写
    Linux查看库依赖方法
    判断当前所使用python的版本和来源
  • 原文地址:https://www.cnblogs.com/randysun/p/12248905.html
Copyright © 2011-2022 走看看