風_月无边

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

定义一个类,具有一个属性name

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

1、继承时直接覆盖init方法,增加属性age,则Student不含name属性,输出name报错

class Student(Person):
    def __init__(self,age):
        self.age = age
lihua = Student(10)
print(lihua.age)
print(lihua.name)

 

 2、使用super().__init__()改写init()方法,增加一个属性age,此时构造的Student类可以调用name和age属性

class Student(Person):
    def __init__(self,age):
        super(Student,self).__init__()
        self.age = age

lihua = Student(10)
print(lihua.age)
print(lihua.name)

 

posted on 2022-03-11 20:53  風_月无边  阅读(106)  评论(0)    收藏  举报