Print moo

>>> class Duck(): ... def quack(self): ... print 'quack!'

<__main__.Cow instance at 0x100491a28> cannot quack quack! >>>

>>> for animal in [animal1, animal2]: ... try:

... except AttributeError:

<__main__.Cow instance at 0x100491a28> cannot quack quack! >>>

In the first iteration, we explicitly check for the availability of the method (we ask for permission) before we call the method. In the second iteration, we call the method without checking if it's available. We then catch the possible exception (we ask for forgiveness) and handle the absence of the method accordingly, if at all.

Was this article helpful?

0 0

Post a comment