Ask coding questions

← Back to all posts
Trouble with Class Inheritance
JosephHaws1 (2)

So, I've been learning about classes in python recently, and needless to say, I think I need help. I've learned enough about classes to the point where I know the basic functionality of a class, however, inheritance is where I'm getting confused. I've gone through several tutorials, which are great for telling me how to use the correct syntax, but none of the tutorials have really touched on how it's useful.

I'm also confused on the entire concept. I get that a child class inherits the attributes of the parent class, after which you can edit the child class attributes to your liking.

But that's the thing: Why do that when you could just make another class? Does it save time? Processing Power? Is it just easier to read? And how do I know which class should inherit from the other? Not a single tutorial has been able to answer these questions in a way that at the very least makes sense to an intermediate level programmer like me.

If you are going to answer this, please do the following:

  • Explain it in the best way possible
  • Cover as much on inheritance as you can (within reason, you don't have to tell me everything, though that would be appreciated)
  • Dumb it down. Me not know big word, but me know small word. (Ok, maybe not that much, but you get the idea)
  • (Optional) Include some useful related info that could possibly help me in other areas

That's basically it. The project below is my attempt at inheritance, feel free to correct any mistakes if you notice any.
Thanks in advance!

Comments
hotnewtop
Coder100 (17126)

Here's why.
Look at this class:

class A: pass

has absolutely NOTHING.
Now suppose you want to change an attribute. Normally you can't:

class A: pass

e = A()
e.attr = 5

that's an error.
Now you would usually just do __init__ right? But what if you don't own that class? What if it was exported by another module? Now, to 'control' it, you have to extend it:

class B(A): __init__(self): self.attr = None
e = B()
e.attr = 5 # yay!

cool