• 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
    -------------------------

    更新....

  • 相关阅读:
    2019 icpc西安邀请赛 点分治
    2019ccpc 秦皇岛
    hdu 5354 树上点分治
    cf 632E FFT+快速幂
    hdu 4812 树分治+逆元+手写hashmap
    2019 上海网络赛G 手写哈希map+字符串hash
    2019 上海icpc网络赛 C FFT优化卷积+小范围暴力
    hdu 6198 杜教BM
    洛谷P3804 后缀自动机
    集合总结
  • 原文地址:https://www.cnblogs.com/Echo-O/p/9398715.html
Copyright © 2020-2023  润新知