zoukankan      html  css  js  c++  java
  • 在子派生的新方法中重用父类功能的两种方式

    方式一: 与继承无关

    指名道姓法,直接用:类名.函数名

    例如:

    # 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) #重用父类的功能
    # self.stu_id=stu_id
    #
    # def choose_course(self):
    # print('%s is choosing course' %self.name)

    方式二:严格以继承属性查找关系

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

              super().__init__(不用为self传值)

    注意:

    super()的完整用法是super(自己的类名,self),再python2中需要些完整,而python3中可以简写为super()

    例如:

    # 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
    # self.stu_id=stu_id
    #
    # def choose_course(self):
    # print('%s is choosing course' %self.name)
    #
    #
    # stu1=OldboyStudent('猪哥',19,'male',1)
    # print(stu1.__dict__)
    #
    # print(OldboyStudent.mro())



    按继承关系查找属性,当有super()的时候:
    例如:
    class A:
    def f1(self):
    print('A.f1')

    class B:
    def f2(self):
    super().f1()
    print('B.f2')

    class C(B,A):
    pass

    obj=C()
    print(C.mro()) #C-》B->A->object
    obj.f2()
    # 先从对象obj里找f2,对象里没有,去类C里找,类c里没有,去父类B里去找,B中有super(),
    # super()会得到一个特殊的对象,该对象就是专门用来访问父类中的属性的(按照继承的关系),,找父类的话,
    # 是按谁触发了super(),就去找谁的父类,再这里是C调用了f2,触发了super,所以应该找
    # C类的父类A。所以,先打印了A,后再执行下面的代码
  • 相关阅读:
    IIS的各种身份验证详细测试
    HTTP Error 401.3 Unauthorized Error While creating IIS 7.0 web site on Windows 7
    C/S and B/S
    WCF ContractFilter mismatch at the EndpointDispatcher exception
    Configure WCF
    Inheritance VS Composition
    Unhandled Error in Silverlight Application, code 2103 when changing the namespace
    Java RMI VS TCP Socket
    Principles Of Object Oriented Design
    Socket处理发送和接收数据包,一个小实例:
  • 原文地址:https://www.cnblogs.com/fxc-520520/p/9234501.html
Copyright © 2011-2022 走看看