class person(): def __init__(self,name): self.name=name @property def a(self): return 'i am a person,my name is %s' %self.name class student(person): def __init__(self,name,age): super(student,self).__init__(name) #self.name=name self.age=age @property def a(self): return 'i am a student,my name is %s' %self.name class teacher(person): def __init__(self,name,score): super(teacher,self).__init__(name) #self.name = name self.score=score @property def a(self): return 'i am a teacher,my name is %s'%self.name def show_a(x): print(x.a) p=person('bob') s=student('alice',12) t=teacher('lily',80) show_a(p) # #i am a person,my name is bob show_a(s) # # i am a student,my name is alice show_a(t) # # i am a teacher,my name is lily
遇上一篇多态的区别:使用了property装饰器,print(x.a())改写成print(x.a),即调用函数的时候不需要再加括号