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?

Rosey
  • 739
  • 1
  • 12
  • 27

0 Answers0