码迷,mamicode.com
首页 > 编程语言 > 详细

Python的多态

时间:2017-09-22 17:47:39      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:ja

实例一:

#!/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())


结果:

Animal is moving...
Animal is moving...
Sheep is moving
Cat is moving
<type ‘int‘>
<type ‘float‘>
M is moving


实例二

#!/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)


本文出自 “小鱼的博客” 博客,谢绝转载!

Python的多态

标签:ja

原文地址:http://395469372.blog.51cto.com/1150982/1967817

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!