2

I am starting to get the hang of OOP. Can someone explain this one concept to me with a python context though? I have a couple classes:

class A(object):
    def __init__(self):
        self.foo = 'hello'

class B(A):
    def __init__(self):
        self.bar = 'world'

So I understand, mechanically that when I make a new __ init __ def in class B it overrides class A's __ init __. But I want to know why.

I want to make a instance of class B with it's own init, but I also want it to have A's init. So far the only solution I know of to get what I want, is to just copy the code from A's __ init __ on top of B's.

So I do:

class A(object):
    def __init__(self):
        self.foo = 'hello'

class B(A):
    def __init__(self):
        self.foo = 'hello'
        self.bar = 'world'

But with object inheritance, I figure there should be a better way to do this. How do most people go about making an init for subclasses, while still inheriting the things from the base class? Do you seriously have to copy paste everything you want into the subclass?

2
  • 2
    Use super and call your parent classes' init inside your child class init Commented Oct 29, 2018 at 15:46
  • 2
    And note, even without super you could always do A.__init__(self) in B's init ... You never should have to copy and paste code. Remember, methods are just functions. You can call them anywhere Commented Oct 29, 2018 at 15:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.