Duck typing
July 14, 2011 in Shots
« If it looks like a duck, and quacks like a duck, it must be a duck »
[Il Duck typing è] il principio secondo il quale il comportamento di una funzione sui suoi argomenti non deve essere determinato dal tipo di questi (come accade in C e altri linguaggi staticamente tipizzati), bensì da quali messaggi essi sono in grado di gestire.
Si riferisce ad uno stile di tipizzazione dinamica dove la semantica di un oggetto è determinata dall’insieme corrente dei suoi metodi e delle sue proprietà anziché dal fatto di estendere una particolare classe o implementare una specifica interfaccia.
[sourcecode language="ruby"]
class Duck(object):
def quack(self):
print “Quaaaaaack!”
def feathers(self):
print “The duck has white and gray feathers.”class Person(object):
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 in_the_forest(duck):
duck.quack()
duck.feathers()def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)game()
‘Quaaaaaak’
‘The duck has white and gray feathers.’
‘The person imitates a duck.’
‘The person takes a feather from the ground and shows it.’
[/sourcecode]
Wikipedia: http://it.wikipedia.org/wiki/Duck_typing












Recent Comments