Python 之 Duck Typing(鸭子类型)

一些例子来源于(http://www.voidspace.org.uk/python/articles/duck_typing.shtml#id8

我们常说,Python是动态语言,而鸭子类型又是动态语言的一种风格。其实,动态是相对于静态来说的。在C++、C #、Java等静态语言中,代码在编译时就已经可以知道变量的类型,方法返回的类型等等一切信息,而在静态语言中,往往要到程序执行的那一刻才知道变量的类型。

a = 1
a = 'ff'
a = [1, 2, 3]

一开始,我们创建了int类型的变量1,并将其name 设为a,然后创建string变量'ff',并将其name 设为a,a 这个name 已经用在'ff' 上面了,而变量1 没有name 绑定,故变量1 将会被内存回收清理掉。(So hasn't a just changed type ? The answer is a resounding no. a isn't an object at all - it's a name. In the first statement we create an integer object with the value 3 and bind the name 'variable' to it. In the second statement we create a new string object with the value 'ff', and rebind the name 'a' to it. If there are no other names bound to the first object (or more properly no references to the object - not all references are names) then it's reference count will drop to zero and it will be garbage collected.

  • 鸭子类型
"If it walks like a duck and it quacks like a duck, then it must be a duck."

当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。”

class Parrot:
    def fly(self):
        print("Parrot flying")

class Airplane:
    def fly(self):
        print("Airplane flying")

class Whale:
    def swim(self):
        print("Whale swimming")

def lift_off(entity):
    entity.fly()

parrot = Parrot()
airplane = Airplane()
whale = Whale()

lift_off(parrot) # prints `Parrot flying`
lift_off(airplane) # prints `Airplane flying`
lift_off(whale) # Throws the error `'Whale' object has no attribute 'fly'`
上面一段代码来自英文维基百科,好好感受一下鸭子类型的魅力吧。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值