博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[py]python多态-动态语言的鸭子类型
阅读量:4693 次
发布时间:2019-06-09

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

弱类型?强类型?动态语言,静态语言

弱类型: 在程序运行过程中,类型可变

1312420-20180119152147896-1972075126.png

动态
variables must necessarily be defined before they are used. But the good thing is that these variables need not be declared, and they need not be bound to a particular type. Python is a very good example of a dynamic typed programming language.

1312420-20180119151814599-1696097507.png

1312420-20180119151849084-322465886.png

1312420-20180119151903396-1147411801.png

- 弱类型:> "1"+2'12'强类型:>>> "1"+2Traceback (most recent call last):  File "
", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects动态类型:>>> a = 1>>> type(a)
>>> a = "s">>> type(a)
静态类型:Prelude> let a = "123" :: Int
:2:9: Couldn't match expected type `Int' with actual type `[Char]' In the expression: "123" :: Int In an equation for `a': a = "123" :: Int

鸭子类型的典故

只要拥有动物的talk方法,就可以去使用meeting方法. 而不必一定要是anaimal的子类, 总得找个合适的比喻来描述吧. 像是鸭子,会叫,就把他当成鸭子, 像是狗会狗叫,就当他是狗, 只不过我们一般用鸭子来比喻.

1312420-20180119152921787-633807356.png

“A bird that walks like a duck and swims like a duck and quacks like a duck, is a duck.”

The actual Apparel of an entity doesn't matter if the entity does all the intended things.

1312420-20180119150503318-293716082.png

In other words, don't check whether it IS-A duck,check whether it QUACKS-like-a duck, WALKS-like-a duck, etc. depending on exactly what subset of duck-like behavior you need for your program.

class Duck:    def quack(self):         print "這鴨子在呱呱叫"    def feathers(self):         print "這鴨子擁有白色與灰色羽毛" class Person:    def quack(self):        print "這人正在模仿鴨子"    def feathers(self):         print "這人在地上拿起1根羽毛然後給其他人看" def in_the_forest(duck):    duck.quack()    duck.feathers() def game():    donald = Duck()    john = Person()    in_the_forest(donald)    in_the_forest(john)game()

转载于:https://www.cnblogs.com/iiiiiher/p/8317136.html

你可能感兴趣的文章
CodeForces 1B
查看>>
win10应用UserControl
查看>>
BZOJ4516: [Sdoi2016]生成魔咒(后缀自动机)
查看>>
查看手机已经记住的WIFI密码
查看>>
最新版IntelliJ IDEA2019 破解教程(2019.08.07-情人节更新)
查看>>
我是怎么用缠论在商品里边抢钱之二 (2019-07-12 15:10:10)
查看>>
python入门之正则表达式
查看>>
SAS学习经验总结分享:篇五-过程步的应用
查看>>
Android创建文件夹及文件并写入数据
查看>>
file的getPath getAbsolutePath和getCanonicalPath的不同
查看>>
课时4—切入切出动画
查看>>
eclipse 编辑 python 中文乱码的解决方案
查看>>
Python 爬虫的集中简单方式
查看>>
数据库MySQL/mariadb知识点——触发器
查看>>
Ubuntu做Tomcat服务:insserv: warning: script 'tomcat' missing LSB tags and overrides
查看>>
Binary Agents
查看>>
入门Webpack,看这篇就够了
查看>>
短信拦截马”黑色产业链与溯源取证研究
查看>>
最小公倍数
查看>>
asp.net如何定时执行任务
查看>>