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

 

 

 

更新....

 posted on 2018-08-11 15:42  全村人的.希望  阅读(2766)  评论(0编辑  收藏  举报