一、为什么要用继承
- 使用继承可以减少代码的冗余
- 两个类实例化两个对象的时候,两个对象具有相同的属性或者相同的方法时,可以把相同的属性或方法在抽取出来定义一个新的基类,用之前的两个类来继承这个新的基类
class Person:
school = 'oldboy'
def __init__(self,name,age):
self.name = name
self.age = age
class Student(Person):
def __init__(self,name,age,course):
Person.__init__(self,name,age)
self.course = course
class Teather(Person):
def __init__(self,name,age,level):
Person.__init__(self,name,age)
self.level = level
stu1 = Student('xichem',18,'python')
t1 = Teather('nick',30,10)
print(stu1.school)
print(stu1.__dict__)
print(t1.__dict__)
oldboy
{'name': 'xichem', 'age': 18, 'course': 'python'}
{'name': 'nick', 'age': 30, 'level': 10}