• python--类的继承


    继承基础

    继承的优点

    新类不用从头编写,复用已有代码

    新类从现有的类继承,就自动拥有了现有类的全部功能

    新类只需要编写现有类缺少的功能

    继承的特点

    子类和父类是一个is关系

    class person(object):
        pass
    class student(person):
        pass
    p = person()
    s = student()

    p是一个person,p不是一个student

    s是一个person,s也是一个student

    总是要从某个类继承,没有就object

    super.__init__()

    此方法用于初始化父类

    def __init__(self,args):
        super(Subclass,self).__init__(args)
        pass

    错误的继承

    student和book是has关系

    class student(book):
        pass

    has关系应该使用组合而非继承

    class person(object):
        pass
    class book(object):
        def __init__(self,name):
            self.name = name
    class student(person):
        def __init__(self,bookName):
            self.book = book(bookName)

    如果已经定义了Person类,需要定义新的Student和Teacher类时,可以直接从Person类继承:

    class Person(object):
        def __init__(self, name, gender):
            self.name = name
            self.gender = gender

    定义Student类时,只需要把额外的属性加上,例如score:

    class Student(Person):
        def __init__(self, name, gender, score):
            super(Student, self).__init__(name, gender)
            self.score = score

    一定要用 super(Student, self).__init__(name, gender) 去初始化父类,否则,继承自 Person 的 Student 将没有 name 和 gender。

    函数super(Student, self)将返回当前类继承的父类,即 Person ,然后调用__init__()方法,注意self参数已在super()中传入,在__init__()中将隐式传递,不需要写出(也不能写)。

  • 相关阅读:
    LeetCode: Trapping Rain Water
    LeetCode: Text Justification
    LeetCode: Unique Paths
    LeetCode: Unique Binary Search Trees
    向Google、Yahoo!和百度提交Sitemap网站地图
    Paypal IPN&PDT变量列表
    SQL查询和删除重复字段的内容
    [C#]基于.net技术的 Rss 订阅开发
    验证码识别流程
    c# string.Format 格式化日期
  • 原文地址:https://www.cnblogs.com/SCCQ/p/12283676.html
Copyright © 2020-2023  润新知