弱类型?强类型?动态语言,静态语言
弱类型: 在程序运行过程中,类型可变
动态 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"+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的子类, 总得找个合适的比喻来描述吧. 像是鸭子,会叫,就把他当成鸭子, 像是狗会狗叫,就当他是狗, 只不过我们一般用鸭子来比喻.
“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()