Python: Inheritance is not templating

This is something I forgot today, which bugged me a lot. Honestly, I don't program a lot, but it's a bit bothersome that I didn't have this piece of knowledge on the top of my mind. The gist is simple, inheritance doesn't work like templating. There's a difference between local variables and class variables.

What I tried the first time:

class Base: x = []

class A(Base): pass

class B(Base): pass

a_inst = A()

b_inst = B()

b_inst.x.append("foo")

a_inst.x.append("bar")

print a_inst.x

print b_inst.x

This resulted in the output:

['foo','bar']

['foo','bar']

That's not what I expected. After asking around a little on #python, I was pointed to my mistake. The code should've been:


class Base:
    def __init__(self):
        self.x = []


class A(Base):
    def __init__(self):
        Base.__init__(self)


class B(Base):
    def __init__(self):
        Base.__init__(self)


a_inst = A()

b_inst = B()



b_inst.x.append("foo")

a_inst.x.append("bar")



print a_inst.x

print b_inst.x

And this give me the expected output:

['bar']

['foo']

Hope this helps someone!

Comments

Comments powered by Disqus