继承super
# from o2 import People # 父类 class People(): sum = 0 def __init__(self, name, age): self.name = name self.age = age def get_name(self): print(self.name) def say(self): print('父类方法') # 子类 class Student(People): def __init__(self, name, age, school): self.school = school # 给父类传递参数,self必须传入self super().__init__(name, age) def say(self): # 调用父类方法 super().say() print('子类方法') student = Student('zhangsan', 18, '第一小学') print(student.name) student.say()
继承不使用super
# from o2 import People # 父类 class People(): sum = 0 def __init__(self, name, age): self.name = name self.age = age def get_name(self): print(self.name) def say(self): print('父类方法') # 子类 class Student(People): def __init__(self, name, age, school): self.school = school # 给父类传递参数,self必须传入self People.__init__(self, name, age) def say(self): # 调用父类方法 People.say(self) print('子类方法') student = Student('zhangsan', 18, '第一小学') print(student.name) student.say()
明显看到如果使用父类名去初始化父类成员的时候,必须传入self,则super不必
如果子类和父类有同样的一个方法,子类优先
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接