Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Classes in Python are basically just ways of grouping a bunch of functions and data.. They are different to classes in C++ and such..</p> <p>I've mostly seen inheritance used for overriding methods of the super-class. For example, perhaps a more Python'ish use of inheritance would be..</p> <pre><code>from world.animals import Dog class Cat(Dog): def speak(self): print "meow" </code></pre> <p>Of course cats aren't a type of dog, but I have this (third party) <code>Dog</code> class which works perfectly, <em>except</em> the <code>speak</code> method which I want to override - this saves re-implementing the entire class, just so it meows. Again, while <code>Cat</code> isn't a type of <code>Dog</code>, but a cat does inherit a lot of attributes..</p> <p>A much better (practical) example of overriding a method or attribute is how you change the user-agent for urllib. You basically subclass <code>urllib.FancyURLopener</code> and change the version attribute (<a href="http://docs.python.org/library/urllib.html#urllib._urlopener" rel="nofollow noreferrer">from the documentation</a>):</p> <pre><code>import urllib class AppURLopener(urllib.FancyURLopener): version = "App/1.7" urllib._urlopener = AppURLopener() </code></pre> <p>Another manner exceptions are used is for Exceptions, when inheritance is used in a more "proper" way:</p> <pre><code>class AnimalError(Exception): pass class AnimalBrokenLegError(AnimalError): pass class AnimalSickError(AnimalError): pass </code></pre> <p>..you can then catch <code>AnimalError</code> to catch all exceptions which inherit from it, or a specific one like <code>AnimalBrokenLegError</code></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