多态即一个接口,多种实现
按照平常直接调用
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name class Student(Person): def talk(self): print(‘%s is studying‘%self.name) class Teacher(Person): def talk(self): print(‘%s is teaching‘%self.name) if __name__ == ‘__main__‘: Student(‘John‘).talk() Teacher(‘Jane‘).talk()
通过定义函数来实现多态
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name class Student(Person): def talk(self): print(‘%s is studying‘%self.name) class Teacher(Person): def talk(self): print(‘%s is teaching‘%self.name) def Person_Talk(n): n.talk() if __name__ == ‘__main__‘: s = Student(‘John‘) t = Teacher(‘Jane‘) Person_Talk(s) Person_Talk(t)
通过父类调用来实现多态
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name @staticmethod def Person_Talk(n): n.talk() class Student(Person): def talk(self): print(‘%s is studying‘%self.name) class Teacher(Person): def talk(self): print(‘%s is teaching‘%self.name) if __name__ == ‘__main__‘: s = Student(‘John‘) t = Teacher(‘Jane‘) Person.Person_Talk(s) Person.Person_Talk(t)
原文地址:https://www.cnblogs.com/sch01ar/p/8361826.html
时间: 2024-09-30 21:47:17