Python类(四)-多态
2024-10-20 01:37:36
多态即一个接口,多种实现
按照平常直接调用
# -*- 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)
最新文章
- jquery dataTable汉化(插件形式)
- [LeetCode] Pow(x, n) 求x的n次方
- calc 的使用
- 007. 自定义ListBox的item的宽高, 字体居中
- 非常非常好!写了好久 k-th-smallest-in-lexicographical-order
- tcprstat源码分析之tcp数据包分析
- iOS开发中使用静态库 .a 文件
- [HTTP] HTTP Verb
- Asp.net MVC中的ViewData与ViewBag(转)
- 【BZOJ1009】GT考试(KMP算法,矩阵快速幂,动态规划)
- SpringBoot入门:新一代Java模板引擎Thymeleaf(理论)
- git >; 2.3 实现同步盘的功能
- 软件测试自动化的最新趋势对开源测试管理软件ITEST的启示
- GIT-windows系统部署gitblit服务器
- [P3625][APIO2009]采油区域 (前缀和)
- deepin使用笔记-解决蓝牙设备开机自动开启的问题
- 安装Numpy方法
- python添加新的模块
- CentOS7切换到root用户和退回普通用户
- background的使用