继承,继承其它实例化样本的属性和方法,需要在声明里重新定义和使用

class School(object):
    def __init__(self, name, addr):
        self.name = name
        self.addr = addr
        self.student = []  # 用于进行学生类的存储
        self.teacher = []  # 用于进行老师类的存储
    def enroll(self, stu_obj):
        print('招录进来学生%s'%stu_obj.name)
        self.student.append(stu_obj) # 将学生类进行添加
    def hire(self, staff_obj):
        print('招募老师%s'%staff_obj.name)
        self.teacher.append(staff_obj) # 将老师类进行添加

class Schoolmember(object):  # 创建学校成员的父类 
    def __init__(self, name, age, sex): # 定义初始变量
        self.name = name  # 定义名字
        self.age = age # 定义年龄
        self.sex = sex  # 定义性别
    def teach(self):  # 定义父类属性
        pass

class Teacher(Schoolmember): # 定义老师属性,继承父类
    def __init__(self, name, age, sex, salary, course): # 变量声明
        super(Teacher, self).__init__(name, age, sex) # 变量继承
        self.salary = salary
        self.course = course
    def tell(self):
        print('''
        ---info---%s
        name %s 
        age %s 
        sex %s 
        salary %s 
        course %s 
        '''%(self.name, self.name, self.age, self.sex, self.salary, self.course))
    def teach(self):
        print('%s is teaching'%self.name)

class Student(Schoolmember):
    def __init__(self, name, age, sex, stu_id, grade):
       super(Student, self).__init__(name, age, sex)
       self.stu_id = stu_id
       self.grade = grade

    def tell(self):
        print('''
           ---info---%s
           name %s 
           age %s 
           sex %s 
           stu_id %s 
           grade %s 
           ''' % (self.name, self.name, self.age, self.sex, self.stu_id, self.grade))
    def paid_tution(self, money):
        print('%s has paid tution for $%s'%(self.name, money))


# 创建实例
school = School('oldboy', '沙河')

s1 = Student('aaa', 22, 'M', '0001', 'python')
s2 = Student('bbb', 23, 'F', '0002', 'linux')

t1 = Teacher('ccc', 333, 'W', 10000, 'python')
t2 = Teacher('ddd', 444, 'F', 20000, 'linux')

school.enroll(s1)
school.hire(t1)
school.teacher[0].teach()
for stu in school.student:
    stu.paid_tution(20000)

多态: 表示在父类里定义一个函数,在子类里都可以使用

class Animal(object):
    def __init__(self, name): # 初始化
        self.name = name 
    @staticmethod  # 静态变量装饰器, 这样不需要输入self变量
    def animal_talk(obj):
        obj.talk()

class dog(Animal): # 定义dog类, 继承Animal 
    def __init__(self, name):
        super(dog, self).__init__(name)

    def talk(self): # 定义函数属性
        print('wowo')


class cat(Animal):
    def __init__(self, name):
        super(cat, self).__init__(name)

    def talk(self):
        print('Meow')

c = cat('aaa') # 实例化
d = dog('bbb')
Animal.animal_talk(c) # 调用Animal里面的属性
Animal.animal_talk(d)

 

posted on 2019-10-16 11:39  python我的最爱  阅读(328)  评论(0编辑  收藏  举报