084 为何要使用继承

1、为何要用继承

  • 使用继承能够减小代码的冗余
  • 两个类实例化两个对象的时候,两个对象具备相同的属性或者相同的方法时,能够把相同的属性或方法在抽取出来定义一个新的基类,用以前的两个类来继承这个新的基类
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}python

相关文章
相关标签/搜索