Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>Duck typing</em> means that an operation does <strong>not formally specify</strong> the requirements that its operands have to meet, but just <strong>tries it out</strong> with what is given.</p> <p>Unlike what others have said, this does not necessarily relate to dynamic languages or inheritance issues.</p> <p><strong>Example task:</strong> Call some method <code>Quack</code> on an object.</p> <p><em>Without</em> using duck-typing, a function <code>f</code> doing this task has to specify in advance that its argument has to support some method <code>Quack</code>. A common way is the use of interfaces</p> <pre><code>interface IQuack { void Quack(); } void f(IQuack x) { x.Quack(); } </code></pre> <p>Calling <code>f(42)</code> fails, but <code>f(donald)</code> works as long as <code>donald</code> is an instance of a <code>IQuack</code>-subtype.</p> <p>Another approach is <a href="http://en.wikipedia.org/wiki/Structural_type_system" rel="noreferrer"><em>structural typing</em></a> - but again, the method <code>Quack()</code> is formally specified any anything that cannot prove it <code>quack</code>s in advance will cause a compiler failure.</p> <pre><code>def f(x : { def Quack() : Unit }) = x.Quack() </code></pre> <p>We could even write</p> <pre><code>f :: Quackable a =&gt; a -&gt; IO () f = quack </code></pre> <p>in Haskell, where the <code>Quackable</code> typeclass ensures the existence of our method.</p> <p><hr> So how does <strong>duck typing</strong> change this? </p> <p>Well, as I said, a duck typing system does not specify requirements but <em>just tries if anything works</em>.</p> <p>Thus, a dynamic type system as Python's always uses duck typing:</p> <pre><code>def f(x): x.Quack() </code></pre> <p>If <code>f</code> gets an <code>x</code> supporting a <code>Quack()</code>, everything is fine, if not, it will crash at runtime.</p> <p>But duck typing doesn't imply dynamic typing at all - in fact, there is a very popular but completely static duck typing approach that doesn't give any requirements too:</p> <pre><code>template &lt;typename T&gt; void f(T x) { x.Quack(); } </code></pre> <p>The function doesn't tell in any way that it wants some <code>x</code> that can <code>Quack</code>, so instead it just tries <em>at compile time</em> and if everything works, it's fine.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload