前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python的多态

Python的多态

作者头像
py3study
发布2020-01-10 10:56:57
4940
发布2020-01-10 10:56:57
举报
文章被收录于专栏:python3

实例一:

代码语言:javascript
复制
#!/usr/bin/env python
#coding:utf-8
"""
什么是多态?
1、一种类型具有多种类型的能力
2、允许不同的对象对同一消息做出灵活的反映
pytyon 中的多态
1、通过继承实现多态(子类可作为父类使用)
2、子类通过重载父类的方法实现多态
动态语言与鸭子模型
1、变量绑定的类型具有不确定性
2、函数和方法可以接收任何类型的参数
3、调用方法时不检查提供的参数类型
4、调用时是否成功由参数的方法和属性确定
5、调用不成功则抛出错误
6、Python中不用定义接口
"""
class Animal:
    def move(self):
        print 'Animal is moving...'
class Dog(Animal):
    pass
def move(obj):
    obj.move()
class Cat(Animal):
    def move(self):
        print 'Cat is moving'
class Sheep(Animal):
    def move(self):
        print 'Sheep is moving'
a=Animal()
move(a)
d=Dog()
move(d)
move(Sheep())
move(Cat())
a=12
a=1.2
a=Cat()
def tst(foo):
    print type(foo)
tst(3)
tst(3.3)
class M:
    def move(self):
        print 'M is moving'
move(M())

结果:

代码语言:javascript
复制
Animal is moving...
Animal is moving...
Sheep is moving
Cat is moving
<type 'int'>
<type 'float'>
M is moving

实例二

代码语言:javascript
复制
#!/usr/bin/env python
#coding:utf-8
class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y
 
    def __add__(self,oth):
        return Point(self.x + oth.x , self.y + oth.y)
 
    def info(self):
        print(self.x,self.y)
 
# class D3Point(Point):
#     def __init__(self,x,y,z):
#         super().__init__(x,y)
#         self.z = z
 
#     def __add__(self,oth):
#         return D3Point(self.x + oth.x , self.y + oth.y , self.z + oth.z)
 
#     def info(self):
#         print(self.x,self.y,self.z)
 
class D3Point:
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
 
    def __add__(self,oth):
        return D3Point(self.x + oth.x , self.y + oth.y , self.z + oth.z)
 
    def info(self):
        print(self.x,self.y,self.z)
 
 
def myadd(a,b):
    return a + b  #相同的类型才能相加,调用的是__add__方法
 
if __name__ == '__main__':
    myadd(Point(1,2),Point(3,4)).info()  #(4, 6)
    myadd(D3Point(1,2,3),D3Point(4,5,6)).info() #(5, 7, 9)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档