2024年08月04日 python高级教程 面向对象 Python51
1. 继承的定义
class Person(object): # 定义一个父类 def run(self): # 父类中的方法 print("person is runing") class Chinese(Person): # 定义一个子类, 继承Person类 def walk(self): # 在子类中定义其自身的方法 print('person is walking') c = Chinese() c.run() # 调用继承的Person类的方法 c.walk() # 调用本身的方法 # 输出 person is truning person is walking
2. 构造函数的继承
继承类的构造方法:
1.经典类的写法: 父类名称.__init__(self,参数1,参数2,…) 2. 新式类的写法:super(子类,self).__init__(参数1,参数2,….)
class Person(object): def __init__(self, name, age): self.name = name self.age = age def run(self): print("person is runing") class Chinese(Person): def __init__(self, name, age, language): Person.__init__(self, name, age) # 可写成super(Chinese,self).__init__(name,age) 继承父类的init self.language = language # 定义子类属性 def walk(self): print('person is walking') c = Chinese('xiaoming', 26, 'Chinese')
3. 子类对父类方法的重写
由于子类自身的优先级高于父类,所以当我们在子类定义与父类同名函数即可实现对父类方法的重写
class Person(object): def __init__(self, name, age): self.name = name self.age = age def run(self): print("person is runing") class Chinese(Person): def __init__(self, name, age, language): Person.__init__(self, name, age) self.language = language print(self.name, self.age, self.language) def run(self): # 子类 重写方法 print('%s is also runing chinese' % self.name) c = Chinese('xiaoming', 26, 'Chinese') c.run() # 输出 xiaoming 26 Chinese xiaoming is also runing chinese
本文链接:http://so.lmcjl.com/news/9962/