打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
pyton的多态

pyton的多态

(2013-01-18 16:21:21)
标签:

杂谈

分类: python

多态意味着可以对不同的对象使用同样的操作,但它们可能会以多种形态呈现出结果。

在Python中,任何不知道对象到底是什么类型,但又需要对象做点什么的时候,都会用到多态。

方法多态

class calculator: 
    def count(self,args):
        return 1

calc=calculator() 
from random import choice
obj=choice(['hello,world',[1,2,3],calc]) 
print obj
print type(obj)
print obj.count('a')

对于一个临时对象obj,它通过Python的随机函数取出来,不知道具体类型(是字符串、元组还是自定义类型),都可以调用count方法进行计算,至于count由谁(哪种类型)去做怎么去实现我们并不关心。

运算符多态


def add(x,y):
    return x+y

print add(1,2) #输出3

print add("hello,","world") #输出hello,world


鸭子类型的多态

class Duck:
    def quack(self):
        print "Quaaaaaack!"
    def feathers(self):
        print "The duck has white and gray feathers."
 
class Person:
    def quack(self):
        print "The person imitates a duck."
    def feathers(self):
        print "The person takes a feather from the ground and shows it."
 
def in_the_forest(duck):
    duck.quack()
    duck.feathers()
 
def game():
    donald = Duck()
    john = Person()
    in_the_forest(donald)  #in_the_forest函数的参数是类的实例。
    in_the_forest(john)
 
game()


就in_the_forest函数而言,参数对象是一个鸭子类型,它实现了方法多态。但是实际上我们知道,从严格的抽象来讲,Person类型和Duck完全风马牛不相及。


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
一篇文章带你搞懂Python中的继承和多态
多态及多态性和鸭子类型
分类:
极简python教程08:封装、多态和继承
Json概述以及python对json的相关操作
python 面向对象全面详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服