[py]python多态-动态语言的鸭子类型

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

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

还有一种说法:
动态
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.

弱类型、强类型、动态类型、静态类型语言的区别是什么?

- 弱类型:
> "1"+2
'12'

强类型:
>>> "1"+2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

动态类型:
>>> a = 1
>>> type(a)
<type 'int'>
>>> a = "s"
>>> type(a)
<type 'str'>

静态类型:
Prelude> let a = "123" :: Int

<interactive>: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的子类, 总得找个合适的比喻来描述吧. 像是鸭子,会叫,就把他当成鸭子, 像是狗会狗叫,就当他是狗, 只不过我们一般用鸭子来比喻.

“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.


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