Duck typing duck type program design and Python implementation example, ducktyping
In programming, duck type (English: duck typing) is a dynamic style. In this style, the valid semantics of an object is determined not by inheriting from a specific class or implementing a specific interface, but by the set of current methods and attributes.
The concept comes from the duck test proposed by James Whitcomb Riley. The duck test can be described as follows:
"When you see a bird walking like a duck, swimming like a duck, or screaming like a duck, this bird can be called a duck ."
In the duck type, the focus is not on the object type, but on how it is used. For example, in a language that does not use the duck type, we can write a function that accepts an object of the duck type and calls its method of going and calling. In a duck-type language, such a function can accept an object of any type and call its methods. If the methods to be called do not exist, a runtime error is thrown. Any object that has such a correct walk and call method can be accepted by the function leads to the above expression. This method of determining the type is named.
Duck types usually benefit from the type of parameters in non-Test methods and functions, but rely on documents, clear code, and tests to ensure proper use. Users who change from a static type language to a dynamic type language usually try to add some static (before running) type checks, which affects the benefits and scalability of the duck type, it also limits the dynamic features of the language.
Python sample code
As mentioned above, it may be a space hole. For example, in Python, there are many file-like items, such as StringIO, GzipFile, and socket. They have many identical methods. We use them as files.
Another example is list. in the extend () method, we do not care whether its parameter is list or not. As long as it is iteratable, its parameter can be list/tuple/dict/string/generator.
Duck type is often used in dynamic languages and is very flexible, so that python does not want to create a lot of design patterns like java.
The following example uses duck typing to implement polymorphism.
#coding=utf-8 class Duck: def quack(self): print "Quaaaaaack!" class Bird: def quack(self): print "bird imitate duck." class Doge: def quack(self): print "doge imitate duck." def in_the_forest(duck): duck.quack() duck = Duck() bird = Bird() doge = Doge() for x in [duck, bird, doge]: in_the_forest(x)
Let's look at another example,
Let's take a look at the hack output stream.
Import sys. stdout = open ('stdout. log', 'A') # As long as it is file-like, no matter what type of print 'foo' sys. stdout = sys. _ stdout _ # restore print 'bar'
In this way, the output stream is written to the file.