子类继承父类构造函数

子类继承父类构造函数

   运维菜鸟     2021年1月20日 10:14     813    

定义一个父类命名为Person

定义一个子类命名为Student,其继承Person

1)如果子类里边不对__init__进行重写的话,在实例化子类的时候,其会自动调用父类的__init__方法。

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

   
def introduce(self):
       
print("my name is " + self.name)
       
print("I'am %d years old." %(self.age))

class Student(Person):
   
pass

if
__name__ == '__main__':
    zhao = Student(
"zhao" , 20)
    zhao.introduce()


运行结果:

my name is zhao

I'am 20 years old.

根据结果可以知道其调用了父类的构造函数。

 

2)子类重写了父类的__init__,其就不会调用父类的__init__

class Person(object):
   
def __init__(self, name, age):
       
print("call father")
       
self.name = name
       
self.age = age

   
def introduce(self):
       
print("my name is " + self.name)
       
print("I'am %d years old." %(self.age))

class Student(Person):
   
def __init__(self, name, age , score):
       
print("call child")
       
self.name = name
       
self.age = age
       
self.score = score

if __name__ == '__main__':
    zhao = Student(
"zhao" , 20 , 80)
    zhao.introduce()


运行结果:

call child

my name is zhao

I'am 20 years old.

这里可以看到是调用了子类的构造函数。打印出了call child这句话。

 

3)重写了子类的__init__并且调用父类的构造方法。

父类名称.__init__(self,参数1,参数2...)

或者使用以下

super(子类,self).__init__(参数1,参数2....)

class Person(object):
   
def __init__(self, name, age):
       
print("call father")
       
self.name = name
       
self.age = age

   
def introduce(self):
       
print("my name is " + self.name)
       
print("I'am %d years old." %(self.age))

class Student(Person):
   
def __init__(self, name, age , score):
       
# Person.__init__(self , name ,age)
       
super(Student,self).__init__(name , age)
       
print("call child")
       
self.score = score

   
def GetScore(self):
       
print("my score is " + str(self.score))

if __name__ == '__main__':
    zhao = Student(
"zhao" , 20 , 80)
    zhao.introduce()
    zhao.GetScore()


 

运行结果:

call father

call child

my name is zhao

I'am 20 years old.

my score is 80

 

def __init__(self, name, age , score):
    Person.
__init__(self , name ,age)
   
print("call child")
   
self.name = "zhang"
   
self.score = score


如果要是在子类的构造方法中给一个参数赋值的话,就会覆盖掉父类中的参数的值。

运行结果:

call father

call child

my name is zhang

I'am 20 years old.

my score is 80


文章评论

0

其他文章