Duck Typing - Concept Examples

Concept Examples

Consider the following pseudo-code for a duck-typed language:

function calculate(a, b, c) => return (a+b)*c example1 = calculate (1, 2, 3) example2 = calculate (, 2) example3 = calculate ('apples ', 'and oranges, ', 3) print to_string example1 print to_string example2 print to_string example3

In the example, each time the calculate function is called, objects without related inheritance may be used (numbers, lists and strings). As long as the objects support the "+" and "*" methods, the operation will succeed. If translated to Ruby or Python, for example, the result of the code would be:

9 apples and oranges, apples and oranges, apples and oranges,

Thus, duck typing allows polymorphism without inheritance. The only restriction that function calculate places on its variables is that they implement the "+" and the "*" methods.

The duck test can be seen in the following example (in Python). As far as the function in_the_forest is concerned, the Person object is a duck:

class Duck: def quack(self): print("Quaaaaaack!") def feathers(self): print("The duck has white and gray feathers.") class Person: def quack(self): print("The person imitates a duck.") def feathers(self): print("The person takes a feather from the ground and shows it.") def name(self): print("John Smith") def in_the_forest(duck): duck.quack duck.feathers def game: donald = Duck john = Person in_the_forest(donald) in_the_forest(john) game

Read more about this topic:  Duck Typing

Famous quotes containing the words concept and/or examples:

    One concept corrupts and confuses the others. I am not speaking of the Evil whose limited sphere is ethics; I am speaking of the infinite.
    Jorge Luis Borges (1899–1986)

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)