类的派生

1、派生

  • 派生:子类中新定义的属性的这个过程叫作派生,而且须要记住子类在使用派生的属性时始终以本身的为准

90-类的派生-基因遗传.jpg?x-oss-process=style/watermark

1.1 派生方法一(类调用)

  • 指名道姓访问某一个类的函数:该方式与继承无关
class OldboyPeople:
    """因为学生和老师都是人,所以人都有姓名、年龄、性别"""
    school = 'oldboy'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


class OldboyStudent(OldboyPeople):
    """因为学生类没有独自的__init__()方法,所以不须要声明继承父类的__init__()方法,会自动继承"""

    def choose_course(self):
        print('%s is choosing course' % self.name)


class OldboyTeacher(OldboyPeople):
    """因为老师类有独自的__init__()方法,所以须要声明继承父类的__init__()"""

    def __init__(self, name, age, gender, level):
        OldboyPeople.__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 = OldboyStudent('tank', 18, 'male')
tea1 = OldboyTeacher('nick', 18, 'male', 10)
print(stu1.__dict__)
{'name': 'tank', 'age': 18, 'gender': 'male'}
print(tea1.__dict__)
{'name': 'nick', 'age': 18, 'gender': 'male', 'level': 10}

1.2 派生方法二(super)

  • 严格以来继承属性查找关系函数

  • super()会获得一个特殊的对象,该对象就是专门用来访问父类中的属性的(按照继承的关系)code

  • super().__init__(不用为self传值)对象

  • super的完整用法是super(本身的类名,self),在python2中须要写完整,而python3中能够简写为super()blog

class OldboyPeople:
    school = 'oldboy'

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


class OldboyStudent(OldboyPeople):
    def __init__(self, name, age, sex, stu_id):
        # OldboyPeople.__init__(self,name,age,sex)
        # super(OldboyStudent, 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 = OldboyStudent('tank', 19, 'male', 1)
print(stu1.__dict__)
{'name': 'tank', 'age': 19, 'sex': 'male', 'stu_id': 1}
相关文章
相关标签/搜索