
继承父亲的方法
子类可以直接调用父类的方法
classPerson(): def__init__(self): pass defhello(self): print'hello' classStudent(Person): def__init__(self): pass s=Student() s.hello() #hello
继承父类属性
这里要注意, 假如要继承父类的属性, 父类的构造函数必须在子类的构造函数中调用, 否则会报错,无法访问, 因为父类的结构函数没有被调用, 构造函数中的属性自然没有声明
此时,如果调用父类属性,就会报错, 报错内容是Student实例没有name属性
#coding=utf-8
classPerson():
def__init__(self):
self.name='小明'
self.age=18
print('Personclassinitcompleted')
defhello(self):
print'hello'
classStudent(Person):
def__init__(self):
print('Studentclassinitcompleted')
s=Student()
prints.name
#Studentclassinitcompleted
#Traceback(mostrecentcalllast):
#File".\classDemo.py",line23,in<module>
#prints.name
#AttributeError:Studentinstancehasnoattribute'name'以下是子类在构造函数中调用父类构造函数的情况, 子类实例可以访问父类属性
#coding=utf-8
classPerson():
def__init__(self):
self.name=u'小明'
self.age=18
print('Personclassinitcompleted')
defhello(self):
print'hello'
classStudent(Person):
def__init__(self):
Person.__init__(self)
print('Studentclassinitcompleted')
s=Student()
prints.name
#Personclassinitcompleted
#Studentclassinitcompleted
#小明方法重写
有时父类提供的方法不能满足需求, 父类的方法可以在子类中重写
在父类Person中, 构造函数只定义了name和age两个属性, print_into()函数只打印name, age这两个属性
在子类Student中, 多了一个schol属性, 显然,父类的提供方法功能还不够, 这时候, 子类需要重写父类的方法, 扩展父类功能
#coding=utf-8 classPerson(object): def__init__(self,name,age): self.name=name self.age=age defprint_info(self): print'name:',self.name print'age:',self.age classStudent(Person): def__init__(self,name,age,school): Person.__init__(self,name,age) self.school=school defprint_info(self): super(Student,self).print_info() #super()可直接用于python3 #Python2通常是super(class,self),而且class应该是新的类别 #新类是由内置类型衍生出来的类 print'school:',self.school s=Student(u'小明',18,u'蹲在家里大学') s.print_info() #name:小明 #age:18 #school:家里蹲大学
更多技术请关注Python视频教程。