zoukankan      html  css  js  c++  java
  • Python中类的__init__继承

    Python中类的__init__继承


     概念:

     定义父类

    In [10]: class Person:
       ....:     def __init__(self,name,age,sex):
       ....:         self.name = name
       ....:         self.age = age
       ....:         self.sex = sex
       ....:     def get_name(self):
       ....:         print('name:',self.name)
       ....:  
    In [11]: Bob = Person('Bob',18,'男')
    
    In [12]: Bob.get_name()
    name: Bob

    【1】子类不重写__init__,实例化子类时,会自动调用父类定义的__init__

    In [13]: class Person_child(Person):
       ....:     def get_name(self):
       ....:         print('name:',self.name)
       ....:         
    
    In [14]: child = Person_child('baby',2,'')
    
    In [15]: child.get_name()
    name: baby

    【2】另一种的验证方式

    class Person:
        def __init__(self,name,age):
            self.name = 'Bob'
            self.age = 18
    
        def get_name(self):
            print('name:',self.name)
    
    class Student(Person):
        def get_name(self):
            print('name:',self.name)    
    
    Kevin = Student('Kevin',12)
    print('-------------------------')
    print(Kevin.name)    
    print(Kevin.age)    
    print('-------------------------')
    
    output
    -------------------------
    Bob
    18
    -------------------------

    【3】但重写了__init__时,实例化子类,就不会调用父类已经定义的__init__

    In [17]: class Person_child(Person):
       ....:     def __init__(self,name,age,sex):
       ....:         self.name = name
       ....:         self.age = age
       ....:         self.sex = sex
       ....:     def get_name(self):
       ....:         print('child_name:',self.name)
       ....:         
    
    In [18]: K = Person_child('Kevin',16,'')
    
    In [19]: K.get_name()
    child_name: Kevin

    【4】为了能使用或扩展父类的行为,最好显示调用父类的__init__方法

    class Person:
        def __init__(self,name,age):
            self.name = 'Bob'
            self.age = 18
    
        def get_name(self):
            print('name:',self.name)
    
    class Student(Person):
        def __init__(self,name,age,sex):
            super(Student,self).__init__(name,age)
            self.sex = sex
    
        def get_detail(self):
            print('详细信息:',self.name,'---',self.age,'---',self.sex)
    
            
    
    Kevin = Student('Kevin',12,'')
    print('-------------------------')
    print(Kevin.name)    
    print(Kevin.age)    
    print(Kevin.sex)
    print(Kevin.get_detail())    
    print('-------------------------')
    
    # output
    -------------------------
    Bob
    18
    男
    详细信息: Bob --- 18 --- 男
    None
    -------------------------

    更新....

  • 相关阅读:
    VFL使用
    深复制与浅复制&&strong,copy修饰符总结
    数组的三种查找方法
    开发技巧-代码块使用
    2 duplicate symbols for architecture“文件冲突”
    利用echarts画折线图圆饼
    tab栏切换2
    利用highcharts.js画圆饼
    tab切换
    file上传图片并展示
  • 原文地址:https://www.cnblogs.com/Echo-O/p/9398715.html
Copyright © 2011-2022 走看看