博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python_多态
阅读量:3972 次
发布时间:2019-05-24

本文共 1789 字,大约阅读时间需要 5 分钟。

# 1、什么多态:同一事物有多种形态# class Animal:#     pass## class People(Animal):#     pass## class Dog(Animal):#     pass## class Pig(Animal):#     pass# 2、为何要有多态=》多态会带来什么样的特性,多态性#    多态性指的是可以在不考虑对象具体类型的情况下而直接使用对象class Animal: # 统一所有子类的方法    def say(self):        print('动物基本的发声频率。。。',end=' ')class People(Animal):    def say(self):        super().say()        print('嘤嘤嘤嘤嘤嘤嘤')class Dog(Animal):    def say(self):        super().say()        print('汪汪汪')class Pig(Animal):    def say(self):        super().say()        print('哼哼哼')obj1=People()# print(People.mro())# obj2=Dog()# obj3=Pig()## obj1.say()# obj2.say()# obj3.say()# 定义统一的接口,接收传入的动物对象# def animal_say(animal):#     animal.say()## animal_say(obj1)# animal_say(obj2)# animal_say(obj3)# print('hello'.__len__())# print([1,2,3].__len__())# print({'a':1,'b':2}.__len__())## def my_len(val):#     return val.__len__()# print(my_len('hello'))# print(my_len([1,2,3]))# print(my_len({'a':1,'b':2}))# len('hello')# len([1,2,3])# len({'a':1,'b':2})# python推崇的是鸭子类型# class Cpu:#     def read(self):#         print('cpu read')##     def write(self):#         print('cpu write')## class Mem:#     def read(self):#         print('mem read')##     def write(self):#         print('mem write')### class Txt:#     def read(self):#         print('txt read')##     def write(self):#         print('txt write')### obj1=Cpu()# obj2=Mem()# obj3=Txt()## obj1.read()# obj1.write()## obj2.read()# obj2.write()## obj3.read()# obj3.write()# 了解:import abcclass Animal(metaclass=abc.ABCMeta): # 统一所有子类的标准    @abc.abstractmethod    def say(self):        pass# obj=Animal() # 不能实例化抽象类自己class People(Animal):    def say(self):        passclass Dog(Animal):    def say(self):        passclass Pig(Animal):    def say(self):        pass## obj1=People()# obj2=Dog()# obj3=Pig()

转载地址:http://zbxki.baihongyu.com/

你可能感兴趣的文章
Django 结构及处理流程分析
查看>>
在django中使用logging模块
查看>>
python logging现学现用 – TimedRotatingFileHandler使用方法
查看>>
Django开发中整合新浪微博API
查看>>
python logging
查看>>
一个改进的logger类
查看>>
python 获取当前位置所在的函数名和行号
查看>>
python的logging库中TimedRotatingFileHandler类问题
查看>>
2012年7月编程语言排行榜:Objective-C超越C++
查看>>
J2EE快速开发框架Wabacus 3.4发布,开发效率提高5倍以上
查看>>
用Xmanager连接linux服务器
查看>>
集成问题
查看>>
HashCode的作用
查看>>
Linux服务器上安装tomcat
查看>>
crontab举例
查看>>
Django request 信息
查看>>
长连接与短连接
查看>>
ztree实例
查看>>
python str的一些方法
查看>>
Comet技术
查看>>